+ All Categories
Home > Documents > 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til...

1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til...

Date post: 18-Jan-2016
Category:
Upload: nickolas-spencer
View: 220 times
Download: 0 times
Share this document with a friend
Popular Tags:
46
1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2
Transcript
Page 1: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

1

Opbygning af en Java klasseAbstraktion og modulariseringObject interaktionIntroduktion til Eclipse

Java kursus dag 2

Page 2: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion 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

Page 3: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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

Page 4: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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.

Page 5: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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

Page 6: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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

Page 7: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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;}

Page 8: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

8

Passing Data Through Parameters

Page 9: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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.

Page 10: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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

Page 11: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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

Page 12: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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;}

Page 13: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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

Page 14: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

14

Decisionspublic void insertMoney(int amount){ if(amount > 0) { balance += amount; } else { System.out.println("Use a positive amount: " + amount); }}

Page 15: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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

Page 16: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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); }

Page 17: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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

Page 18: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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.

Page 19: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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.)

Page 20: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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.

Page 21: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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

Page 22: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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

Page 23: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

23

AbstractionReality

???

Models

Tecnology:Hardware, O/S,network, server, etc. .

Software----------------------

----------------------

----------------------

Solutions

Abstraction

Implementation

Page 24: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

24

Modularizing the Digital Clock

One four-digit display?

Or two two-digit displays?

Page 25: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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}

Page 26: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

26

Class Diagram of the Digital ClockStatic view

Page 27: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

27

Object Diagram of the Digital ClockDynamic view

Page 28: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

28

Primitive Types vs. Object Types

32

SomeObject a;

int a;

Object type

Primitive type

Page 29: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

29

Primitive Types vs. Object Types

32

SomeObject a;

int a;

SomeObject b;

b = a;

int b;32

Page 30: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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

Page 31: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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

Page 32: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

32

Implementing the NumberDisplay

public String getDisplayValue(){ if(value < 10) return "0" + value; else return "" + value;}

Page 33: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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(); }}

Page 34: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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();}

Page 35: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

35

Object Diagram of the Digital Clock

Page 36: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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

Page 37: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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

Page 38: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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()

{

}

………

}

Page 39: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

39

Summary

AbstractionModularizationClass diagram (static)Object diagram (dynamic)Primitive typesObject typesObject creationInternal/external method call

Page 40: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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

Page 41: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

Another example

CustomerNumberNameAddressphone

OrderNumberDateDeliveryDatepayDatestatus Product

IdDescriptionPrice Stock

PartOrderamount

1

1

11

Page 42: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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; }}

Page 43: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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;

}

Page 44: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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; }

Page 45: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

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; }

}

Page 46: 1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.

Exercise Customer – Order –PartPrint out information about an order


Recommended