Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2."— Presentation transcript:

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

2 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 Return values Methods may return values as a result of the operation 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 3

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

5 Basic Class Structure 5 public class TicketMachine { Inner part of the class omitted. } public class ClassName { Fields Constructors Methods } The outer wrapper of 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 6 public class TicketMachine { private int price; private int balance; private int total; //Constructor and methods omitted. } private int price; visibility modifiertypevariable name

7 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 7 public TicketMachine(int ticketCost) { price = ticketCost; balance = 0; total = 0; }

8 Passing Data Through Parameters 8

9 Assignment Values are stored into fields (and other variables) via assignment statements: = ; Example: price = ticketCost; A variable stores a single value, so any previous value is lost. 9

10 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 int getPrice() The body encloses the method’s statements 10 public int getPrice() { return price; } return type method name parameter list (empty) start and end of method body (block) return statement visibility modifier

11 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 11 public void insertMoney(int amount) { balance += amount; } return type ( void ) method name parameter visibility modifier assignment statement field being changed

12 Printing From Methods 12 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; }

13 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 13

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

15 Decisions 15 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 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 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 18 public int refundBalance() { int amountToRefund; amountToRefund = balance; balance = 0; return amountToRefund; } A local variable No visibility modifier 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.

19 Data Types 19 A 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 exist Primitive 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. 20

21 Exercises Blue J Native Ticket Machine: Solve exercise: 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 21

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 22

23 Abstraction 23 Reality ??? Models Tecnology: Hardware, O/S, network, server, etc.. Software ----- ------- ---- ------ ----- ------- ---- ------ ----- ------- ---- ------ Solutions Abstraction Implementation

24 Modularizing the Digital Clock 24 One four-digit display? Or two two-digit displays?

25 Implementing the Digital Clock 25 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 Clock 26 Static view

27 Object Diagram of the Digital Clock 27 Dynamic view

28 Primitive Types vs. Object Types 28 32 SomeObject a; int a; Object type Primitive type

29 Primitive Types vs. Object Types 29 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; } 30 ‘Modulo' operator – refer to next slide

31 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

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

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

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

35 Object Diagram of the Digital Clock 35

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(); } } 36 Formal parameter Actual parameter

37 Method Calls Internal method calls ( parameter-list ) External method calls. ( parameter-list ) Examples public ClockDisplay() { updateDisplay(); … public void timeTick() { minutes.increment(); … 37 Internal method call External method call

38 A New Pattern – Class Association 38 AB public class A {……… private B myB; public A{ myB = new B(); } …………….. } public class B { private …… public B() { } ……… }

39 Summary Abstraction Modularization Class diagram (static) Object diagram (dynamic) Primitive types Object types Object creation Internal/external method call 39

40 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 40

41 Another example Customer Number Name Address phone Order Number Date DeliveryDate payDate status Product Id Description Price Stock PartOrder amount 1 1 1 1

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

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

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

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

46 Exercise Customer – Order –Part Print out information about an order


Download ppt "1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2."

Similar presentations


Ads by Google