1
Opbygning af en Java klasseAbstraktion og modulariseringObject interaktionIntroduktion til Eclipse
Java kursus dag 2
2
Recap From Previous Session
ClassesRepresent all objects of a kind (example: “a car”)
ObjectsRepresent 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
AttributesObjects are described by attributes stored in fields
MethodsObjects have “operations” which can be invoked
ParametersMethods may have parameters to pass additional information needed to execute
Return valuesMethods may return values as a result of the operation
3
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
4
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.
5
Basic Class Structure
public class TicketMachine{ Inner part of the class omitted.}
public class ClassName{ Fields Constructors Methods}
The outer wrapperof TicketMachine
The contents of a class
6
Fields
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
public class TicketMachine{ private int price; private int balance; private int total; //Constructor and methods omitted.}
private int price;
visibility modifier type variable name
7
Constructors
Constructors initialize an objectThey have the same name as their classThey store initial values into the fieldsThey often receive external parameter values for this
public TicketMachine(int ticketCost){ price = ticketCost; balance = 0; total = 0;}
8
Passing Data Through Parameters
9
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.
10
Accessor Methods (get())Methods implement the behaviour of objectsAccessors provide information about an objectMethods have a structure consisting of a header and a bodyThe header defines the method’s “signature”
public int getPrice()The body encloses the method’s statements
public int getPrice(){ return price;}
return type
method nameparameter list (empty)
start and end of method body (block)
return statement
visibility modifier
11
Mutator Methods (set())
Have a similar method structure: header and bodyUsed to “mutate” (i.e., change) an object’s stateAchieved through changing the value of one or more fields
Typically contain assignment statementsTypically receive parameters
public void insertMoney(int amount){ balance += amount;}
return type (void)method name
parametervisibility modifier
assignment statement
field being changed
12
Printing From Methodspublic 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;}
13
Reflecting on the Ticket Machines
Their behaviour is inadequate in several waysNo checks on the amounts enteredNo refundsNo checks for a sensible initialization
How can we do better?We need more sophisticated behaviour
14
Decisionspublic void insertMoney(int amount){ if(amount > 0) { balance += amount; } else { System.out.println("Use a positive amount: " + amount); }}
15
Decisions
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}
‘if’ keyword boolean condition to be tested - gives a true or false result
actions if condition is true
actions if condition is false‘else’ keyword
16
If-sætning
if (count == 0){ System.out.println(”No, value were entered.”);}else{ double average = sum/count; System.out.println(”The average is ” + average); }
17
If sætning i if sætning
if (height <= 20){ System.out.println(”Situation Normal”); } else{ System.out.println(”Bravo!”); }}
if (code = = ’R’){
It may be better to make a method if you get to many nested if
18
Variable Types
public int refundBalance(){ int amountToRefund; amountToRefund = balance; balance = 0; return amountToRefund;}
A local variable
No visibilitymodifier
Instance variables (also called object attributes and fields)Describes the attribute of an object, and is accessible throughout the classSame scope as the object (value is stored as long as the object lives)
Local variablesUsed temporarily within the method of a class, and is thus only accessible within the given method.
19
Data TypesA data type is characterized by A set of values (which the data type accepts)Data representation (how are the values stored)A set of operations (the operations to be applied on the data type)
Two main categories existPrimitive types (int, long, boolean, char etc.)Object types (strings, references etc.)
20
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.
21
Exercises Blue JNative Ticket Machine:Solve exercise:
2.20 - Constructor2.21 – 2.27 methods2.28 - test2.29 – 2.30, 2.32 new methods for the class2.33 – 2.38 Print method2.39 – 2.42 improvements
22
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
23
AbstractionReality
???
Models
Tecnology:Hardware, O/S,network, server, etc. .
Software----------------------
----------------------
----------------------
Solutions
Abstraction
Implementation
24
Modularizing the Digital Clock
One four-digit display?
Or two two-digit displays?
25
Implementing the Digital Clock
NumberDisplay:
public class NumberDisplay{ private int limit; private int value;
// constructors and // methods omitted}
ClockDisplay:
public class ClockDisplay{ private NumberDisplay hours; private NumberDisplay minutes;
// constructors and // methods omitted}
26
Class Diagram of the Digital ClockStatic view
27
Object Diagram of the Digital ClockDynamic view
28
Primitive Types vs. Object Types
32
SomeObject a;
int a;
Object type
Primitive type
29
Primitive Types vs. Object Types
32
SomeObject a;
int a;
SomeObject b;
b = a;
int b;32
30
Implementing the NumberDisplay
public NumberDisplay(int rollOverLimit){ 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 % 3What are all possible results of: n % 5
32
Implementing the NumberDisplay
public String getDisplayValue(){ if(value < 10) return "0" + value; else return "" + value;}
33
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(); }}
34
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();}
35
Object Diagram of the Digital Clock
36
The Parameter - Terminology
public NumberDisplay(int rollOverLimit){ limit = rollOverLimit; value = 0;}
public class ClockDisplay{ public ClockDisplay() { hours = new NumberDisplay(24); minutes = new NumberDisplay(60); updateDisplay(); }}
Formal parameter
Actual parameter
37
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
38
A New Pattern – Class Association
A B
public class A
{………
private B myB;
public A{
myB = new B();
}
……………..
}
public class B
{
private ……
public B()
{
}
………
}
39
Summary
AbstractionModularizationClass diagram (static)Object diagram (dynamic)Primitive typesObject typesObject creationInternal/external method call
40
Exercises
3.5, 3.6, 3.7, 3.8 Clock-display3.13, 3.14 –3.25 Clock-display
(3.15 – 3.19 are not exercises to the clock-display)
BankExercise01 BankExercise02CarExercise
Another example
CustomerNumberNameAddressphone
OrderNumberDateDeliveryDatepayDatestatus Product
IdDescriptionPrice Stock
PartOrderamount
1
1
11
public class Customer{ // instance variables private int number; private String address; private String phone; private Order myOrder;//at the moment only one instance of order
/** * Constructor for objects of class Customer */ public Customer(int newNr, String newAddress, String newPhone) { number = newNr; address = newAddress; phone = newPhone; }
public void setOrder(Order newOrder) { myOrder = newOrder; }}
public class Order{ // instance variables private int number; private String orderDate; private String delivery; private String payDate; private boolean status; private PartOrder myPartOrder;// at the moment only one partorder pr. order
public Order(int newNr, String dato, String newDelivery) { number = newNr; orderDate = dato; delivery = newDelivery; status = false; } public void setPartOrder(PartOrder newPart) { 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(int newAmount, Order newOrder, Product newProduct) { amount = newAmount; order = newOrder; product = newProduct; }
public class Product{ // instance variables private int id; private String description; private double price; private int amountOnStock;
/** * Constructor for objects of class Product */ public Product(int newId, String newDescription, double newPrice, int newStock) { id = newId; description = newDescription; price = newPrice; amountOnStock = newStock; }
}
Exercise Customer – Order –PartPrint out information about an order
Top Related