Java the UML Way http www tisip noJava

  • Slides: 28
Download presentation
Java the UML Way http: //www. tisip. no/Java. The. Uml. Way/ Inheritance and Polymorphism

Java the UML Way http: //www. tisip. no/Java. The. Uml. Way/ Inheritance and Polymorphism Repetition from chapter 4 Generalization og specialization Inheritance Polymorphism The renovation case What if polymorphism didn't exist? When do we need instanceof? Access modifiers Two levels of inheritance Rules and definitions Interface versjon 2002 -04 -17 page 2 -3 page 4 -5 page 6 -7 page 8 -10 page 11 -12 page 13 page 14 page 15 -17 page 18 page 19 -24 page 25 -28 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ Chapter 12

the superclass for all other classes From chapter 4 Object set. Background() and Component

the superclass for all other classes From chapter 4 Object set. Background() and Component get. Background() are inherited from here A Segment of the Java Class Tree the subclass for Object and Component Container the superclass for JComponent JPanel and Drawing add() is inherited from here Panel JPanel Applet Drawing JApplet Simple. Applet Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 2

The Objects the Different Classes Describe Form Sets From chapter 4 Container JComponent JPanel

The Objects the Different Classes Describe Form Sets From chapter 4 Container JComponent JPanel Drawing Panel Applet JApplet Simple. Applet Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 3

Generalization and Specialization specializations, subclasses Only to be used in connection with the book

Generalization and Specialization specializations, subclasses Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 4

What Tells the Class Tree? Material A flooring is a material. A paint is

What Tells the Class Tree? Material A flooring is a material. A paint is a material. A wallpaper is a material. Flooring Paint All floorings make a subset of all materials. All paints make a subset of all materials. All wallpapers make a subset of all materials. Wallpaper Solve the problem, page 342. A class tree shows a relationship between classes. A class is a generalization/specialization of another class. The arrow has the direction from the specialized class to the generalized class. Don't confuse associations with generalization/specialization! An association between two classes means that there is a connection between the objects in the two classes. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 5

Inheritance • • A subclass inherits non-private members for the suberclass. Examples: A client

Inheritance • • A subclass inherits non-private members for the suberclass. Examples: A client may send the following messages to a Flooring object: – – – get. Name() get. Price. Per. Unit() get. Total. Price() get. Width() get. Material. Req() Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 6

What About the (Private) Data in the Superclass? • An instance of the Wallpaper

What About the (Private) Data in the Superclass? • An instance of the Wallpaper class has the instance variables from the Material class (name and price) as part of itself, but they may only be accessed via methods inherited from Material. Brocade 500 12 0. 6 can only be accessed via get methods private in the Wallpaper class Wallpaper the. Wallpaper = new Wallpaper ("Brocade", 500, 12, 0. 6); Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 7

Polymorphism • • • The formulas for calculating the material requirement is different for

Polymorphism • • • The formulas for calculating the material requirement is different for flooring, paint and wallpaper. It is possible to calculate the requirement for every type of material. The get. Material. Req() is polymorphous (= ” the quality or state of being able to assume different forms”). The method is abstract in the Material class (it is not possible to state one common formula for all types of materials). The class is abstract because it contains (at least) one abstract method. It is not possible to instantiate objects of an abtract class. • To be able to create instances of a subclass, this subclass needs to have an implementation of the get. Material. Req() method. The class is concrete. • The fact that get. Material. Req() is an (abstract) method in the Material class tells that it is possible to send the get. Material. Req() message to every object which is an instance of a concrete subclass of the Material class. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 8

e) fac r u S e (th q e ial. R r e t

e) fac r u S e (th q e ial. R r e t t. Ma a. Paint double area = a. Surface. get. Area(); double no. Of. Liters = area * no. Of. Coats / no. Of. Sq. MPer. Liter; int no. Of. Liters. Integer = (int) no. Of. Liters; double more = no. Of. Liters - no. Of. Liters. Integer; if (more >= 0. 5 + limit) return no. Of. Liters. Integer + 1. 0; else if (more >= limit) return no. Of. Liters. Integer + 0. 5; else return no. Of. Liters. Integer; ge double length. Surface = a. Surface. get. Length(); double width. Surface = a. Surface. get. Width(); int no. Of. Widths = (int)(length. Surface / width. Of. Flooring); double remnant = length. Surface % width. Of. Flooring; if (remnant >= limit) no. Of. Widths++; return no. Of. Widths * width. Surface; get. Material. Req(the. Surface) get. M ater client ial. R eq(t a. Flooring he. S urfa ce) a. Wallpaper Solve the problems, pp. 344 -345. double length. Surface = a. Surface. get. Length(); double height. Surface = a. Surface. get. Width(); /* calculate the number of heights */ int no. Of. Heights = (int) (length. Surface / width. Per. Roll); double remnant = length. Surface % width. Per. Roll; if (remnant >= limit) no. Of. Heights++; /* calculate the number of rolls */ int no. Of. Rolls; int no. Of. Heights. Per. Roll = (int) (length. Per. Roll / height. Surface); if (no. Of. Heights. Per. Roll > 0) { no. Of. Rolls = no. Of. Heights / no. Of. Heights. Per. Roll; remnant = no. Of. Heights % no. Of. Heights. Per. Roll; if (remnant >= limit) no. Of. Rolls++; } else { // the roll is shorter than one height (rarely!) Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 9

Show Program Listing 12. 1 (pp. 346 -349) and 12. 2 (pp. 351 -352).

Show Program Listing 12. 1 (pp. 346 -349) and 12. 2 (pp. 351 -352). Solve the Problems 2 -4, pp. 350 -351. Solve the Problems 1, 3 and 4, pp. 353 -354. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 10

Class Diagram for Renovation Project with Many Surfaces and Many Materials Only to be

Class Diagram for Renovation Project with Many Surfaces and Many Materials Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 11

The Renovation Project with Many Surfaces and Many Materials, Coding the Program From chapter

The Renovation Project with Many Surfaces and Many Materials, Coding the Program From chapter 10: Now, in chapter 12: class Renovation. Project { private String name; private Array. List all. Surfaces = new Array. List(); private Array. List all. Paints = new Array. List(); class Renovation. Project { private String name; private Array. List all. Surfaces = new Array. List(); private Array. List all. Materials = new Array. List(); public Material add. New. Material(Material new. Material) { Material this. Material = get. Material(new. Material. get. Name()); if (this. Material == null) { all. Materials. add(new. Material); return new. Material; } else return this. Material; public Paint add. New. Paint(Paint new. Paint) { Paint this. Paint = get. Paint(new. Paint. get. Name()); if (this. Paint == null) { all. Paints. add(new. Paint); return new. Paint; } else return this. Paint; } A reference to Material may be set to refer to an instance of a subclass of Material. Our new version of the renovation program may handle many different materials, in spite of very few changes from the former version. We make the most of inheritance og polymorphism. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 12

What If Polymorphism Didn't Exist? • What does polymorphism do for us? – In

What If Polymorphism Didn't Exist? • What does polymorphism do for us? – In this example, it lets us handle different types of materials as a whole. – We send the message get. Material. Req() to an object that is an instance of a subclass of Material. – The object itself knows how it should calculate the materials needed. • What if the objects themselves didn’t know how the need should be calculated? – Then somewhere or other we would have had to make an if-else-if-else sequence (something like this): if (material instanceof Paint) {. . formulas for calculating paint requirements } else if (material instanceof Flooring) {. . formulas for calculating covering requirements } else {. . formulas for calculating wallpaper requirements } • Consider one more time if you think you need to use instanceof combined with an ifelse-if-else sequence. – To do this, evaluate if it is better to make an abstract method in a common superclass for the classes involved and thus let every individual class get its own implementation for the method. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 13

When Do We Need to Use the Operator instanceof? • • We need to

When Do We Need to Use the Operator instanceof? • • We need to use instanceof in conjunction with class trees in those cases where we will send a message to only one part of a subtree. We create the following objects: A object 1 = new C(); A object 2 = new E(); • We can safely send the message method 1() to both of the objects: object 1. method 1(); object 2. method 1(); • A We can only send the message method 2() to subclasses of the class B. if (object 1 instanceof B) { B an. Object = (B) object 1; an. Object. method 2(); } method 2() abstract in B B E C F method 1() abstract in A D method 1() implemented here method 2() implemented here Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 14

Access Modifiers • • • The scope of a name is the part of

Access Modifiers • • • The scope of a name is the part of the program where the name may be used without qualifying it. The accessibility for a name outside its scope is determined by the access modifier (private, public, protected or nothing, nothing = package) placed in front of the name. Classes: – All classes up to now, except for the applets, have been accessible only in the package where they were declared (package access). – The applets have public access. They are accessible from everywhere. • Members and constructors: – private int number; – protected int get. Minimum. Value() { // accessible from the same package // and from subclasses (under // certain conditions) – public int get. Number() { – int get. Secret. Number() { // package access • Class access overrides member/constructor access: – Example: For a member (or a constructor) to have public access, both the member (or the constructor) and the class must be declared public. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 15

The Access for Constructors and Members Declared in the Class C package A package

The Access for Constructors and Members Declared in the Class C package A package B class C private subclass to class C package* protected public *) package means no access modifier Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 16

Recommended Use of Access Modifiers • Instance variables and class variables are always private.

Recommended Use of Access Modifiers • Instance variables and class variables are always private. • Constants are usually public, but can be private if they are not of interest outside the class. • Constructors are usually public. • Methods are usually private or public. • Constructors and methods can be protected if there is no point in using them outside subclasses. • About classes: – As a point of departure, classes have package access (no access modifier). This also limits the access to public constructors and members of the class. – Classes that will be taken into general use are made public and added to a named package. Then all public constructors and members will also automatically become public. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 17

Two Levels of Inheritance Show program listing 12. 4 pp. 365 -367. Only to

Two Levels of Inheritance Show program listing 12. 4 pp. 365 -367. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 18

The abstract Modifier • An abstract class: abstract class Material { …. etc. –

The abstract Modifier • An abstract class: abstract class Material { …. etc. – cannot insantiate objects of an abstract class – may or may not contain or inherit sbtract methods – may contain both abstract and concrete methods • An abstract method: abstract method head; – A class that inherits, or declares on its own, an abstract method, has to be declared abstract. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 19

The super Keyword • super can be used in two ways: – In a

The super Keyword • super can be used in two ways: – In a constructor to invoke the constructor in the direct superclass, for example: public Second. Sort. Flooring(String init. Name, double init. Price, double init. Width) { super(init. Name, init. Price, init. Width); } • The call to super() has to be the first statement in the constructor body. • The arguments to super() must be in accordance with the parameter list of one of the constructors in the direct superclass. – In a method we may use super as a qualifier to refer to a hidden or overriden name in a superclass, for example: public double get. Material. Req(Surface a. Surface) { double basic. Req = super. get. Material. Req(a. Surface); return basic. Req * material. Addendum; } • We cannot write super() or something like that, to refer to a constructor or a method more than one level above in the class tree. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 20

Constructors • If we don’t call a specific constructor in the direct superclass by

Constructors • If we don’t call a specific constructor in the direct superclass by calling super(), a constructor with no arguments will be called. • If this doesn’t exist, the compiler will give an error message. • If the intent is not to make instances of a class, this can be prevented in two ways: – Make the class abstract. This is used if the class has or can have subclasses. – Make all constructors private. This is used if the class cannot have subclasses (it is final, see slide 23). Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 21

Flooring 2 References and Casting First. Sort. Flooring • • Second. Sort. Flooring Assume

Flooring 2 References and Casting First. Sort. Flooring • • Second. Sort. Flooring Assume that all the classes in the figure are concrete. A reference to a class can be set to point to instances of a subclass to the class. It cannot be set to point to instances of a superclass. Examples: Material a. Material = new First. Sort. Flooring("Super. Duper", 140, 5); // ok First. Sort. Flooring fine. Flooring = new Second. Sort. Flooring("Super. Duper 2", 140, 6); // not ok First. Sort. Flooring very. Fine. Flooring = new Flooring 2("Super. Duper 1", 140, 5); // not ok • Assume that we have a reference to an object. – The reference can be cast to the class the object is an instance of, or to superclasses of this class. – It’s not allowed to cast the reference to a subclass of the class that the object is an instance of. – Invalid casting gives a Class. Cast. Exception. Examples: Object an. Object = new Flooring 2("Super. Duper", 140, 5); // ok Flooring 2 a. Flooring = (Flooring 2) an. Object; // ok First. Sort. Flooring fine. Flooring = (First. Sort. Flooring) a. Flooring; // not ok First. Sort. Flooring very. Fine. Flooring = (First. Sort. Flooring) an. Object; // not ok Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 22

The final Modifier • final prevents subclassing and overriding. • A final method cannot

The final Modifier • final prevents subclassing and overriding. • A final method cannot be overridden nor hidden: public final double get. Width() { return width. Of. Flooring; } • It is not possible to subclass a final class: final class Second. Sort. Flooring extends Flooring 2 { …. osv. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 23

Overriding or Hiding a Name • Overriding an inherited instance method – If a

Overriding or Hiding a Name • Overriding an inherited instance method – If a class declares an instance method, this declaration will override any inherited method there might be with the same signature. – The compiler gives an error message if the return type is not right and/or the level of access is less strict than in the overridden method. – An instance method cannot override an inherited class method. This method replaces the inherited version of the get. Material. Req() method • class Second. Sort. Flooring extends Flooring 2 { …. . public double get. Material. Req(Surface a. Surface) { double basic. Req = super. get. Material. Req(a. Surface); return basic. Req * material. Addendum; } } Here we refer to the method which is replaced with the new version. We may hide inherited names of variables and class methods. We do not use this in this book. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 24

Repetition from chapter 10. • • • Interface An interface, simply put, is a

Repetition from chapter 10. • • • Interface An interface, simply put, is a collection of method heads. A class can choose to implement an interface. Then all the methods in the interface have to be programmed. An example from the java. lang package is: public interface Comparable { public int compare. To(Object obj); } • Example of a class implementing this interface: class Surface implements Comparable { public int compare. To(Object obj) { // comparing areas Surface the. Other. Surface = (Surface) obj; double area 1 = get. Area(); // the area of this double area 2 = the. Other. Surface. get. Area(); if (area 1 < area 2 - 0. 0001) return -1; // comparing decimal numerals else if (area 1 > area 2 + 0. 0001) return 1; else return 0; } Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 25

To Create Your Own Interfaces Access modifier public or nothing (package access) public abstract

To Create Your Own Interfaces Access modifier public or nothing (package access) public abstract implied for methods public static final implied for variables interface My. Comparable { boolean greater. Than(Object obj); boolean less. Than(Object obj); boolean equal(Object obj); } interface Constants { int min = 1000; int max = 9999; } An interface is abstract. It is not possible to instantiate objects of an interface. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 26

Implementation of Interfaces class Four. Digits. Number implements Constants, My. Comparable { private int

Implementation of Interfaces class Four. Digits. Number implements Constants, My. Comparable { private int value; public Four. Digits. Number(int init. Value) { if (init. Value < min) value = min; else if (init. Value > max) value = max; else value = init. Value; } public int get. Value() { return value; } public boolean greater. Than(Object obj) { Four. Digits. Number number = (Four. Digits. Number) obj; return (value > number. get. Value()); } public boolean less. Than(Object obj) { Four. Digits. Number number = (Four. Digits. Number) obj; return (value < number. get. Value()); } public boolean equal(Object obj) { Four. Digits. Number number = (Four. Digits. Number) obj; return (value == number. get. Value()); } } The class may use all constants declared in the Constants interface. The class must have an implementation of every method in the My. Comparable interface, or it will be abstract. Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 27

Using the Four. Digits. Number Class class Ex. Interface { public static void main(String[]

Using the Four. Digits. Number Class class Ex. Interface { public static void main(String[] args) { Four. Digits. Number number 1 = new Four. Digits. Number(700); Four. Digits. Number number 2 = new Four. Digits. Number(1700); Four. Digits. Number number 3 = new Four. Digits. Number(70000); System. out. println(number 1. get. Value()); System. out. println(number 2. get. Value()); System. out. println(number 3. get. Value()); System. out. println(number 1. greater. Than(number 2)); System. out. println(number 1. less. Than(number 2)); System. out. println(number 1. equal(number 2)); } } • • /* Example Run: 1000 1700 9999 false true false */ A reference of an interface type may refer to instances of classes that implements the interface: – – Four. Digits. Number number 1 = new Four. Digits. Number(700); Four. Digits. Number number 2 = new Four. Digits. Number(1700); – – System. out. println(number 1. greater. Than(number 2)); // ok System. out. println(number 1. get. Value()); // not ok No other messages than those declared in the interface may be sent to the object: Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0 -470 -84386 -1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http: //tisip. no/engelsk/ 28