460 likes | 608 Views
Java kursus dag 2. Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse. Recap From Previous Session. Classes Represent all objects of a kind (example: “a car”) Objects
E N D
Java kursus dag 2 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse
Recap From Previous Session • Classes • Represent all objects of a kind (example: “a car”) • Objects • Represent specific items from the real world, or from some problem domain (example: “the red car out there in the parking lot”) • An object is an instance of a class – arbitrarily instances can be created • Attributes • Objects are described by attributes stored in fields • Methods • Objects have “operations” which can be invoked • Parameters • Methods may have parameters to pass additional information needed to execute • Returnvalues • Methodsmayreturnvalues as a result of the operation
Programming Style • Class names are singular nouns starting with a capital letter • Student, LabClass • Method and variable names start with lower-case letters • makeVisible, calculateVAT
Ticket Machine – Inside Perspective • Interaction with an object provides clues about it’s behaviour. • Looking inside allows us to determine how that behaviour is provided or implemented. • All Java classes have a similar-looking internal view.
Basic Class Structure The outer wrapper of TicketMachine public class TicketMachine { Inner part of the class omitted. } public class ClassName { Fields Constructors Methods } The contents of a class
Fields public class TicketMachine { private int price; private int balance; private int total; //Constructor and methods omitted. } Fields store values for an object They are also known as instance variables Use the Inspect option to view an object’s fields Fields define the state of an object visibility modifier type variable name private int price;
Constructors Constructors initialize an object They have the same name as their class They store initial values into the fields They often receive external parameter values for this public TicketMachine(intticketCost) { price = ticketCost; balance = 0; total = 0; }
Assignment • Values are stored into fields (and other variables) via assignment statements: • <variable> = <expression>; • Example: price = ticketCost; • A variable stores a single value, so any previous value is lost.
Accessor Methods (get()) Methods implement the behaviour of objects Accessors provide information about an object Methods have a structure consisting of a header and a body The header defines the method’s “signature” public intgetPrice() The body encloses the method’s statements method name parameter list (empty) return type visibility modifier public intgetPrice() { return price; } return statement start and end of method body (block)
Mutator Methods (set()) Have a similar method structure: header and body Used to “mutate” (i.e., change) an object’s state Achieved through changing the value of one or more fields • Typically contain assignment statements • Typically receive parameters method name parameter return type (void) visibility modifier public void insertMoney(int amount) { balance += amount; } assignment statement field being changed
Printing From Methods public void printTicket() { // Simulate the printing of a ticket. System.out.println("##################"); System.out.println("# The BlueJ Line"); System.out.println("# Ticket"); System.out.println("# " + price + " cents."); System.out.println("##################"); System.out.println(); // Update the total collected with the balance. total = total + balance; // Clear the balance. balance = 0; }
Reflecting on the Ticket Machines • Their behaviour is inadequate in several ways • No checks on the amounts entered • No refunds • No checks for a sensible initialization • How can we do better? • We need more sophisticated behaviour
Decisions public void insertMoney(int amount) { if(amount > 0) { balance += amount; } else { System.out.println("Use a positive amount: " + amount); } }
Decisions boolean condition to be tested - gives a true or false result ‘if’ keyword actions if condition is true if(perform some test) { Do the statements here if the test gave a true result } else { Do the statements here if the test gave a false result } actions if condition is false ‘else’ keyword
If-sætning if(count == 0){ System.out.println(”No, valuewereentered.”); } else { double average = sum/count; System.out.println(”The average is ” + average); }
If sætning i if sætning if (code = = ’R’){ if(height <= 20){ System.out.println(”Situation Normal”); } else{ System.out.println(”Bravo!”); } } It maybebetter to make a methodifyouget to manynestedif
Variable Types Instance variables (also called object attributes and fields) Describes the attribute of an object, and is accessible throughout the class Same scope as the object (value is stored as long as the object lives) Local variables Used temporarily within the method of a class, and is thus only accessible within the given method. A local variable public int refundBalance() { int amountToRefund; amountToRefund = balance; balance = 0; return amountToRefund; } No visibility modifier
Data Types • A data type is characterized by A set of values (which the data type accepts) Data representation (howare the valuesstored) A set of operations (the operations to beappliedon the data type) • Twomaincategoriesexist Primitive types (int, long, boolean, char etc.) Object types (strings, references etc.)
Summary • Class bodies contain fields, constructors and methods. • Fields store values that determine an object’s state. • Constructors initialize objects. • Methods implement the behaviour of objects. • Fields, parameters and local variables are all variables. • Fields persist for the lifetime of an object. • Parameters are used to receive values into a constructor or method. • Local variables are used for short-lived temporary storage. • Objects can make decisions via conditional (if) statements. • A true or false test allows one of two alternative courses of actions to be taken.
Exercises Blue J • NativeTicketMachine: • Solveexercise: • 2.20 - Constructor • 2.21 – 2.27 methods • 2.28 - test • 2.29 – 2.30, 2.32 new methods for the class • 2.33 – 2.38 Print method • 2.39 – 2.42 improvements
Abstraction and Modularization • Abstraction • is the ability to ignore details of parts to focus attention on a higher level of a problem • Modularization • is the process of dividing a whole into well-defined parts, which can be built and examined separately, and which interact in well-defined ways
Models Abstraction Solutions Reality ??? Tecnology: Hardware, O/S, network, server, etc. . Abstraction Software ----- ------- ---- ------ ----- ------- ---- ------ Implementation ----- ------- ---- ------
Modularizing the Digital Clock One four-digit display? Or two two-digit displays?
Implementing the Digital Clock • ClockDisplay: • public class ClockDisplay • { • private NumberDisplay hours; • private NumberDisplay minutes; • // constructors and • // methods omitted • } NumberDisplay: public class NumberDisplay { private int limit; private int value; // constructors and // methods omitted }
Class Diagram of the Digital Clock Static view
Object Diagram of the Digital Clock Dynamic view
Primitive Types vs. Object Types SomeObject a; Object type Primitive type int a; 32
Primitive Types vs. Object Types SomeObject a; SomeObject b; b = a; int a; intb; 32 32
Implementing the NumberDisplay public NumberDisplay(introllOverLimit) { limit = rollOverLimit; value = 0; } public void increment() { value = (value + 1) % limit; } • ‘Modulo' operator – refer to next slide
The Modulo Operator The 'division' operator (/), when applied to int operands, returns the result of an integer division. The 'modulo' operator (%) returns the remainder of an integer division. Generally: 17 / 5 = result 3, remainder 2 In Java: 17 / 5 = 3 17 % 5 = 2 What is the result of: 8 % 3 What are all possible results of: n % 5
Implementing the NumberDisplay public String getDisplayValue() { if(value < 10) return "0" + value; else return "" + value; }
Objects Creating Objects public class ClockDisplay { private NumberDisplay hours; private NumberDisplay minutes; private String displayString; public ClockDisplay() { hours = new NumberDisplay(24); minutes = new NumberDisplay(60); updateDisplay(); } }
Object Interaction public void timeTick() { minutes.increment(); if(minutes.getValue() == 0) { // it just rolled over! hours.increment(); } updateDisplay(); } private void updateDisplay() { displayString = hours.getDisplayValue() + ":" + minutes.getDisplayValue(); }
The Parameter - Terminology public NumberDisplay(introllOverLimit) { limit = rollOverLimit; value = 0; } public class ClockDisplay { public ClockDisplay() { hours = new NumberDisplay(24); minutes = new NumberDisplay(60); updateDisplay(); } } Formal parameter Actualparameter
Method Calls Internal method calls <method>( parameter-list ) External method calls <object>.<method>( parameter-list ) Examples public ClockDisplay() { updateDisplay(); … public void timeTick() { minutes.increment(); … Internal method call External method call
A New Pattern – Class Association public class B { private …… public B() { } ……… } A B public class A {……… private B myB; public A{ myB= new B(); } …………….. }
Summary • Abstraction • Modularization • Class diagram (static) • Object diagram (dynamic) • Primitive types • Object types • Object creation • Internal/external method call
Exercises • 3.5, 3.6, 3.7, 3.8 Clock-display • 3.13, 3.14 –3.25 Clock-display • (3.15 – 3.19 are not exercises to the clock-display) • BankExercise01 • BankExercise02 • CarExercise
Another example Customer Number Name Address phone Order Number Date DeliveryDate payDate status 1 1 Product Id Description Price Stock 1 1 PartOrder amount
public classCustomer { // instance variables private intnumber; private Stringaddress; private Stringphone; private OrdermyOrder;//at the moment onlyoneinstance of order /** * Constructor for objects of classCustomer */ public Customer(intnewNr, StringnewAddress, StringnewPhone) { number = newNr; address = newAddress; phone = newPhone; } public voidsetOrder(OrdernewOrder) { myOrder = newOrder; } }
public classOrder { // instance variables private intnumber; private StringorderDate; private Stringdelivery; private StringpayDate; private boolean status; private PartOrdermyPartOrder;// at the moment onlyonepartorder pr. order public Order(intnewNr, String dato, StringnewDelivery) { number = newNr; orderDate = dato; delivery = newDelivery; status = false; } public voidsetPartOrder(PartOrdernewPart) { myPartOrder = newPart; }
public class PartOrder { // instance variables - replace the example below with your own private int amount; private Order order;//is connected to one order private Product product;// is connected to one product /** * Constructor for objects of class PartOrder */ public PartOrder(intnewAmount, Order newOrder, Product newProduct) { amount = newAmount; order = newOrder; product = newProduct; }
public classProduct { // instance variables private int id; private Stringdescription; private double price; private intamountOnStock; /** * Constructor for objects of classProduct */ public Product(intnewId, StringnewDescription, double newPrice, intnewStock) { id = newId; description = newDescription; price = newPrice; amountOnStock = newStock; } }
Exercise Customer – Order –Part • Print out information about an order