0% found this document useful (0 votes)
25 views

M7 Inheritance

Uploaded by

Justin Reynolds
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

M7 Inheritance

Uploaded by

Justin Reynolds
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 104

Programming 1

-1-
Contents
1. Superclass and subclass
2. Inheritance and accessibility
3. Inheriting attributes
4. Inheriting methods
5. Constructors and inheritance
6. Abstract classes
7. The Object class
8. Polymorphism
9. Inheritance vs Aggregation

-2-
Superclass
Subclass
Why inheritance?
Why inheritance? 9.1

•Example: Shop
– A cashier is scanning products
– Each product has a barcode, a description and a price
– The system also provides additional information for
specific types of products
– Book: code, description, price, author, title
– Camera: code, description, price, pixels
– Shirt: code, description, price, size, gender

-4-
Why inheritance? Shop application

Complete UML class diagram

Do you notice anything?


A lot of duplicate code, a.k.a. redundant code!

-5-
Try it out (1): Why inheritance?
•Download
▪ Java M7: Inheritance > Subject Matter
M7_ShopApp-Java_starter_code.zip
•Paste it in your IntelliJ project
•Launch the ShopApp (in package client)
•Navigate through the code and make sure you
understand it. You should recognize all the concepts
we’ve seen during the first term

•So, do you notice the amount of redundant code?

-6-
Why inheritance? Shapes application

Complete UML class diagram

Do you notice anything?


A lot of duplicate
code, a.k.a. redundant
code!

-7-
Exercise (1): Why inheritance?
•Download
– Java M7: Inheritance > Exercises
M7_ShapesApp-Java_starter_code.7z
•Paste it in your IntelliJ project
•Launch the ShapesApp (in package client)
•Navigate through the code and make sure you
understand it. You should recognize all the concepts
we’ve seen during the first term

•So, do you notice the amount of redundant code?

-8-
Solution 9.2

methods not displayed

•Inheritance: tree structure (hierarchy)


– One superclass (Product)
– Multiple subclasses (Book, Camera, Shirt)
•Superclass contains common characteristics
•Subclasses inherit al the characteristics of the
superclass

-9-
extends
•Inheritance is implemented in Java by using
the extends keyword

superclass
(generalization)

extends class
hierarchy

UML generalization subclass


(specialisation)

Generalization relation: ... “is a kind of” …


🡪 A Book is a kind of Product, …
- 10 -
extends

public class Product {


// Body
}

public class Book extends Product {


// Body
}

- 11 -
extends
•Syntax class SubClass extends SuperClass {
// ...
}
•Subclass:
– inherits all the members (attributes and methods) of
the superclass
– can add members
– can replace (override) members
•A class can have only one superclass
(single inheritance)
– Maximum 1 class after extends
– …but, the superclass (parent) can itself extend
another superclass (grandparent)

- 12 -
extends: problem
•Suppose you have a superclass…
public class Vehicle {
private int speed;
public void setSpeed(int speed) {
this.speed += speed;
}
//…
}
•… and you don’t want any subclass to change the
behavior of the superclass, because it might
undermine its correctness
public class MyVehicle extends Vehicle {
public void setSpeed(int speed) {
}
}
This implementation will prevent any MyVehicle from
changing its speed at all. Is that what you want?
- 13 -
extends: solution
•Declare the superclass as final
public final class Vehicle {
private int speed;
public void setSpeed(int speed) {
this.speed += speed;
}
//…
}
•No class can inherit from Vehicle anymore
public class MyVehicle extends Vehicle {
public void setSpeed(int speed) {
}
}

Error:
Cannot inherit from final class ‘Vehicle'

- 14 -
final class: remarks
•Can not be extended
– Can be a design consideration
– Can enhance performance
(see later: Polymorphism)

•By the way, the String class is a final class


package java.lang;

public final class String

- 15 -
Try it out (2): extends
•Add a new class Product
•Make your code correspond to following UML diagram:

- 16 -
Exercise (2): extends
•Add a new class Shape
•Make your code
correspond to following
UML diagram:

- 17 -
Inheritance and
accessibility

18
Inheritance and accessibility
•A subclass inherits all members of a
superclass, data and methods!
•A subclass may or may not be able to access
inherited members, depending on access
modifiers:
– private, protected, package, public

- 19 -
From where can you access a member?

UML same class in same subclass any class


symbol class package
private - x
(package) ~ x x
protected # x x x
public + x x x x

○ private members are only accessible within the class


itself, not from any other (sub)class
○ protected is an access modifier granting access to
subclasses
○ Remark: when there is no explicit access modifier
(package), members are accessible from classes in the
same package (whether they are subclasses are not)
○ public members are accessible from everywhere,
including the subclasses
- 20 -
From where can you access a member?

UML same class in same subclass any class


symbol class package
private - x
(package) ~ x x
protected # x x x
public + x x x x

○ So, only protected and public members in the


superclass are accessible in the subclass
○ Access defaults
○ UML: when there is no access symbol the most
common access level is understood
■ attribute: private
■ method: public

- 21 -
Inheriting
attributes
Inheriting attributes
•For attributes, a subclass can do three things
1. Use inherited attributes
2. Add attributes
3. Override attributes
▪ Is discouraged, so we won't handle it

- 23 -
1. Use inherited attributes 9.4

public class Product {


private String code;
protected String description;
public double price;
}

public class Book extends Product {


public Book() {
code = "CODE1"; --> COMPILER ERROR
description = "Descr.";
price = 0.0;
}
}

Book can access public or protected attributes.


(and package-private if it is in the same package)
- 24 -
1. Use inherited attributes: best practice
•Although protected and public attributes grant
subclasses direct access to them, it is generally
considered bad practice!
•Why?
– Doing so allows subclasses to avoid validations
implemented in the setter of the superclass for
that attribute
•Best practice: never give non-final
attributes protected or public access level
(see course module 5 - Classes: Encapsulation)
– We’ll always define (non-final) attributes
private

- 25 -
2. Add new attributes
•Subclasses can have additional attributes:
– author
– title

Book inherits code,


description and price
additional
attributes

- 26 -
Try it out (3): Inheriting attributes
•Play a little with protected and public attributes, but
don’t forget to put them back to private

- 27 -
Exercise (3): Inheriting attributes
•Play a little with
protected and public
attributes, but don’t
forget to put them
back to private

- 28 -
Inheriting
methods
Inheriting methods
•For methods, a subclass can do three things
1. Use inherited methods
2. Add new methods
3. Override or re-implement inherited methods

- 30 -
1. Use inherited methods
•A subclass is a kind of super
class, meaning
– Any protected or public
superclass method is available to
the subclass

In this example, Book can


• not call setCode (private)
• call setDescription (protected)
• call setPrice (public)

… or any package-private method


when both classes are in the same
package
methods not displayed

- 31 -
1. Use inherited methods: read only attributes
• What are read only attributes?
– Once initialized, other classes can’t
change them
• Can be achieved by playing a little with
access attributes
• Imagine a new user requirement: “After
initialization in the constructor, the code
attribute of Product can not be changed
anymore”
– How can that be achieved?
public void setCode(String code)?
🡺 no: other classes could change it
protected void setCode(String code)?
🡺 yes: no other class can change it Book methods not displayed

- 32 -
1. Use inherited methods: read only attributes
• What are read only attributes?
– Once initialized, other classes can’t
change them
• Can be achieved by playing a little with
access attributes
• Imagine a new user requirement: “After
initialization in the constructor, the code
attribute of Product can not be changed
anymore”
– How can that be achieved?
public void setCode(String code)?
🡺 no: other classes could change it
private void setCode(String code)?
🡺 yes: other class cannot change it
Book methods not displayed

- 33 -
2. Add methods
•A subclass can add extra methods

Book can use 6 inherited methods


+ 5 own methods

(Book has 3 inherited attributes


+ 2 of its own)

additional
methods
constructors not
displayed
- 34 -
3. Override methods
•Overriding: a subclass provides an
inherited method with its own
implementation by reimplementing
the method in its own class
•The redefined method must have
the same signature as the method
defined in the super class
– the same signature (name +
parameter types)
– the method must also have the
same return type
(FYI: or a covariant type)

- 35 -
3. Override methods
public class Product { public class Book extends Product {
// ... // ...

public double getVat() { public double getVat() {


return 0.0; return 0.06;
} }
} }

Book book = new Book();


System.out.printf("VAT for book: %.2f%%%n", book.getVat() * 100);

(output)
VAT for book: 6.00%

- 36 -
3. Override methods: @Override
•Use @Override when overriding the method in the
subclass. The compiler will check whether the method
is correctly overriding a method from its superclass!
public class Book extends Product {
// ...
@Override 🡺 OK
public double getVat() {
return 0.06;
}
}

public class Book extends Product {


// ...
@Override 🡺 COMPILER ERROR
public double getvat() {
return 0.06;
This is not an override, you are
}
actually defining a new method
}
- 37 -
3. Override methods: super
• Overriding a method = replacing the superclass method
• What if you just want to add some extra behavior to it?
– From the overriding method, you can call the superclass
method using the super keyword
public class Product { //...
@Override
public String toString() {
return String.format("%-8s , %-30s , %-6.2f Eur“
, getCode(), getDescription(), getPrice());
} // toString()
} // class

public class Book { //...


@Override
public String toString() {
return String.format("%s author:%-15s title:%s"
, super.toString(), author, title);
} // toString()
} // class
- 38 -
Method overriding: problem
• Suppose you have a superclass…
public class Vehicle {
private int speed;
public void setSpeed(int speed) {
this.speed += speed;
}
//…
}
• … and you don’t want any subclass to change the behavior
of a particular method, because it might undermine the
correctness of that method
public class Car extends Vehicle {
public void setSpeed(int speed) {
}
}
This implementation will prevent any Car from
changing its speed at all. Is that what you want?
- 39 -
Method overriding: solution
• Declare the method as final in the superclass
public class Vehicle {
private int speed;
public final void setSpeed(int speed) {
this.speed += speed;
}
//…
}
• The subclass can’t override that method
public class Car extends Vehicle {
public void setSpeed(int speed) {
}
}

Error:
cannot override setSpeed()' in ‘Car'; overridden method is final

- 40 -
Method overriding: another problem
• Suppose you have a superclass…
public class Person {
private String name;

public Person(String name) {


initialise(); Beware: constructor calling
setName(name); overridable (non final) methods!
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void initialise() {
System.out.println("Person initialising...");
}
}
- 41 -
Method overriding: another problem
• … and following subclass…
public class Employee extends Person {
private int salary;

public Employee(String name, int salary) {


super(name); // invoking baseclass ctor (see later)
//…
} Potential program crash (NullPointerException)
//…
public void initialise() {
String upperCaseName = getName().toUpperCase();
System.out.printf("Employee %s initialising...",
upperCaseName);
} Problem is that the subclass tries to use inherited
} attribute ‘name’ that hasn’t been intialised yet

public static void main(String[] args) {


Person bob = new Employee("Bob", 1000);
}
- 42 -
Method overriding: solution
• Make sure that constructors don’t call methods that can be
overridden → make them final, or set them private
public class Person {
private String name; GOOD PRACTICE
public Person(String name) {
initialise();
setName(name);
}
public String getName() {
return name;
}
public final void setName(String name) {
this.name = name;
}
public final void initialise() {
System.out.println("Person initialising...");
} Normally, we don't write to a console in a library class but
} log to, for instance, a file instead (see Programming 2, M6)
- 43 -
Quiz
•Answer the following questions:
1. Which expressions are correct?
1. class PoliceCar extends Car yes
2. class PoliceCar extends Police, Car no
3. class WhiteCollar imports Employee no

2. class Bonobo inherits from class Ape. They both


override toString(). How would you call Ape's
toString() method from Bonobo?
super.toString()

3. Class Ape has a private method int getAge(). I want to


access the method directly from subclass Chimp. What is the
best access modifier for getAge()? protected

4.
- 44 -
Try it out (4): Inheriting methods
•Make sure the highlighted methods are implemented

getVat()
Product returns 0
Book returns .06
Camera returns 0.21
Shirt returns 0.21

- 45 -
Exercise (4): Inheriting methods
•Make sure the
highlighted methods are
implemented

- 46 -
Exercises
•Ex 07.01 – Ex07.03

- 47 -
9.5

Constructors
and inheritance
Subclass constructor
• Reminder: If you do not explicitly write a constructor, a
class has a default constructor (without parameters)
• Inthe beginning of a subclass constructor, the
compiler by default, adds a call to the constructor
without parameters of the superclass: super()
public class Product {
// …
public Product() {
System.out.println("First initialising a product");
}
}
The constructor of Product was called! Because a
Book is a Product, Product is initialised first!
public class Book extends Product { Book animalFarm = new Book();
// … // prints: First initialising a
public Book() { product
// implicitly calls super()
}
} We do not really need to write this Book() constructor,
it is the same as the default constructor
- 49 -
Subclass constructor: problem
•Now, how to invoke the superclass constructor, when
the superclass doesn’t have a default constructor?
public class Product {
// ...
public Product(String code, String description, double price){
setCode(code);
setDescription(description);
setPrice(price);
}
}

public class Book extends Product {


// …
public Book(String code, String description, double price,
String author, String title) {
setAuthor(author);
Error: There is no default constructor available in Product'
setTitle(title);
}
} The Book constructor tries to call the Product constructor without
parameters, but since we defined another constructor in Product,
no default constructor has been added in Product
- 50 -
Subclass constructor: solution
•Explicitly call an existing constructor of the superclass
– In our example: the 3-parameter Product constructor
public class Product {
// ...
public Product(String code, String description, double price){
setCode(code);
setDescription(description);
setPrice(price);
}
}

public class Book extends Product {


// …
public Book(String code, String description, double price,
String author, String title) {
super(code, description, price);
setAuthor(author);
setTitle(title);
}
}

- 51 -
Subclass constructor: remarks
•If, on the first line of a subclass constructor, you
call another constructor (using super or this),
the compiler does not add a call to the default
constructor of the superclass

•Constructors are not inherited


– but a constructor of the superclass is always,
implicitly or explicitly, called from the
constructor of the subclass

- 52 -
Quiz
1. Why is this code not compiling?
public class Foo { The Bar constructor tries to call
private int foo; the constructor without
Foo(int foo) { this.foo = foo; } parameters in Foo, but this
} constructor does not exist
public class Bar extends Foo {
private int bar;
Bar() { this.bar = bar; }
Bar(int foo, int bar) {
super(foo);
this.bar = bar; }
}
2. What is the problem with this code? Can you find a
solution? Infinite loop!
@Override
public int getX() { Use super.getX();
return getX(); (if that method exists in the
} superclass)

3. What is the purpose of the @Override annotation?


The compiler checks if you are effectively overriding a method in the superclass

- 53 -
Try it out (5): Constructors and inheritance
•Implement the superclass constructor
•Make sure that your code compiles and runs as before
▪ Hint: requires some changes in the subclass constructors

- 54 -
Exercise (5): Constructors and inheritance
•Implement the superclass constructor
•Make sure that your code compiles and runs as before
– Hint: requires some changes in the subclass constructors

- 55 -
10.4

Abstract methods
and classes
New user requirement
•“Every specific Product (Book, Camera, Shirt) must
implement getVat()”
•Does our current code guarantee that?
•What happens when e.g. class Book doesn’t
implement getVat()? So, let’s remove getVat() from
class Book and try the following
Book myBook = new Book(…);
System.out.printf("vat = %.2f \n“ , myBook.getVat());
(output)
vat = 0.00 Wrong: should be 0.06

•Solution? Force subclass Book to provide an


implementation
•How? Define getVat() in class Product as abstract

- 57 -
abstract method
• An abstract method doesn’t have an implementation (body)
public abstract class Product { // … An abstract method has no
public abstract double getVat(); implementation {body}
} // class Declaration ends with a ;
• Must be declared in an abstract class
• Creates the following error in subclass Book
public class Book extends Product { // …
} // class Class 'Book' must either be declared abstract or
implement abstract method 'getVat()' in 'Product'
• This way, the compiler helps us not to ‘forget’ to implement
getVat() public class Book extends Product { // …
@Override
public double getVat() {
return 0.06;
} // getVat()
} // class

- 58 -
abstract class
•So, class Product is now an abstract class
public abstract class Product { // …
public abstract double getVat();
} // class

•No instances can be created from an abstract class


Product justAProduct = new 'Product' is abstract;
Product(…); cannot be instantiated
– Which suits us just fine because we sell Books,
Cameras or Shirts, not just Products
•Can contain a constructor though, but only callable
using super(...) from the subclass constructor
•A class with one or more abstract methods is an
abstract class
– An abstract class doesn’t have to contain abstract
methods
- 59 -
abstract class
•An abstract class contains common attributes and
methods for subclasses
– An abstract method only defines what it does (by its
name), not how it does it (no implementation)
– A concrete subclass must override the abstract
methods it inherits (or become abstract itself)
•UML uses italics to indicate an abstract class or
abstract method

- 60 -
Quiz
1. Abstract class Animal with abstract method
getAge(), has a subclass Mammal.
Which options are possible?
a. class Mammal is also abstract
b. class Mammal implements getAge()
c. I only implement getAge() in class Ape, which
extends Mammal
d. I cannot do anything in the subclass, getAge must be
implemented in Animal
d is wrong

2. An abstract class needs a public or protected


contructor, but you cannot create objects of an
abstract class. Explain.
A subclass constructor always needs to call the superclass
constructor, even if the superclass is abstract

- 61 -
Try it out (6): abstract class and method
•Enforce Book, Camera and Shirt to implement getVat()
•Test that you can not create any instances of class
Product anymore

- 62 -
Exercise (6): abstract class and method
•Enforce Rectangle and Circle to implement
getPerimeter() and getArea()
•Test that you can not create any instances of class
Shape anymore

- 63 -
9.6

The Object
class
Superclass Object
•If you do not specifiy a superclass for a class, it
inherits from java.lang.Object
– The compiler implicitly adds extends Object
•Actually, every Java class directly or indirectly inherits
from java.lang.Object
•Class Object doesn’t have any attributes
•Some common methods that each class inherits from
Object and can/should override:
Returntype Method Description
Returns a string representation of the
object
Indicates whether some other object is
"equal to" this one

Returns a hash code value for the object


Returns the runtime class of this Object

- 65 -
Inheritance and variables

• A Book is a kind of Product, so we can assign a Book to a Product


variable
Product item1 = new Book("123","IT",20.0,"Deitel","Java");
Product item2 = new Camera("456","digital",160.0,8_000_000);
• The opposite is not always true, a Product can be a Book or
something else
Book deitel = item1; // compiler error
• Tell the compiler you know item1 references a Book by explicitly
casting
Book deitel = (Book) item1; // OK
– If you cast a reference to a class it does not refer to, you get a
runtime Exception
Book camera = (Book) item2; Cast Down
// Compiles OK, runtime ClassCastException

Cast Down
You can always assi n a variable of a subclass to a variable of a superclass (widen)
To assi n a variable of a superclass to a variable of a su class you need to cast e plicitly (narrow)
- 66 -
Inheritance and variables

• You can only access attributes/methods from the variable class


Product item1 = new Book("123","IT",20.0,"Deitel","Java");
System.out.println("OK: ", item1.price);
System.out.println("Compiler error: ",item1.author);
System.out.println("OK: ",((Book)item1).author);
– Note: this example supposes the attributes are public

- 67 -
The instanceof operator
• Tests if an object is an instance of a class
– returns false if object is null
• Example

Book b = new Book();


System.out.println(b instanceof Object); true
System.out.println(b instanceof Book); true
System.out.println(b instanceof Comic); false
System.out.println(b instanceof Camera); COMPILER ERROR
- 68 -
The instanceof operator

• instanceof can cast as well (since Java 16)


• Example
Book book = new Comic("789","Lucky Luke",10.0,"Goscinny",
"Ma Dalton","Morris");
if (book instanceof Comic c) {
System.out.println("Illustrations by " +c.artist);
}

How would you have


written this code before
Java 16?

- 69 -
Method getClass()
•When using instanceOf you need to hardcode the
class against which you want to test
•getClass() retrieves the class of an object
•To retrieve the name of the class
Book animalFarm = new Book("George Orwell", "Animal farm");
System.out.printf("%s is a %s \n\n",
animalFarm.getTitle(),
animalFarm.getClass().getSimpleName());

// Generated output: Animal farm is a Book

- 70 -
Method equals()
•The equals(Object other) method compares this
(the current object) with other (another object)
•The default implementation returns true if they refer
to the same object, in other words, if it is the same
object, if their identity is the same
– Implementation in java.lang.Object
public boolean equals(Object other) {
return (this == other);
}

- 71 -
Quiz
•Predict the output
Book animalFarm1 = new Book("George Orwell", "Animal farm");
Book animalFarm2 = new Book("George Orwell", "Animal farm");
Book animalFarm3 = animalFarm2;

System.out.printf("Is equal: %b \n",


animalFarm1.equals(animalFarm2));
System.out.printf("Is equal: %b \n",
animalFarm2.equals(animalFarm3));
System.out.printf("Is equal: %b \n",
animalFarm1.equals(animalFarm3));

(output) false
true
false

- 72 -
Method equals()
•Override equals to compare objects based on the
objects' attribute(s):
public class Camera {
// ...
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
If both have the same identity
}
if (!(other instanceof Camera)) {
return false; The other must be of the same type
}
if (!super.equals(other)) {
return false; Superclass attributes must be equal as
} well!!
Camera camera = (Camera) other; Cast to get access to Camera attributes
return pixels == camera.pixels;
} // equals()
} // class

- 73 -
equals()
• Override equals to compare objects based on
identifying characteristic(s).
public class Rectangle {
// ...
@Override
public boolean equals(Object obj) {
if (obj instanceof Rectangle rect) { check class + cast
return width == rect.width && height == rect.height;
} else {
return false; You can generate equals code (press [ALT]+[INSERT])
Select only identifying attributes!
}

- 74 -
Method hashCode()
•A hash code is an integer value that is associated
with an object (like a checksum)
– Its main purpose is to facilitate hashing in hash tables,
which are used by data structures like Sets and Maps
(see Term 3: Collections)
– Proper operations of those data structures require you
to override equals() as well as hashCode()
•Equal objects must return the same hash code
– If you override equals(), also override hashcode(). The
hashcode calculation should use the same attributes as
the ones used in equals.
– Objects with the same hash code are probably equal

- 75 -
Method hashCode()
•Non-equal objects could return the same hash code,
but usually return different ones
– A String and a Rectangle object for instance could
produce a same hash code
Can generate both equals and hashCode
public class Rectangle { (press [ALT]+[INSERT])
// ...
@Override
public int hashcode() {
return Objects.hash(super.hashCode(), width, height);

}
}

• Objects.hash is a static utility method that combines


multiple hashcodes into one hashcode.
– do not confuse hashcode (Object method that
calculates a hashcode for it) with Objects.hash
(combines multiple hashcodes into one)
- 76 -
Method hashCode()
•Example public class Camera {
// ...
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + pixels;
return result;
} // hashCode()
} // class

•Sometimes, you might see a calculation like this


public class Rectangle {
// ...
@Override
public int hashcode() {
return (x ^ y ^ width ^ height);

^ is the exclusive OR operator


}
}

- 77 -
Intermezzo: Exclusive OR (XOR)
^ (“exclusive or”)
• Yields true if operands are different (one operand is true,
the other is false)
if ((nr1 > 0) ^ (nr2 > 0)) {
int product = nr1 * nr2;
System.out.println(product +
" is a negative number.");
}

• When applied to integral numbers, logical operators operate


on every bit of their binary representation (bitwise)
decimal representation binary representation
6 0 1 1 0
5 0 1 0 1
6^5=3 0 0 1 1

- 78 -
Try it out (7): Object class
•Implement equals() and hashCode() in all classes…

- 79 -
Try it out (7): Object class
•… such that following code in the main class produces
the output (see below)
Book animalFarm1 = new Book("BK001", "Novel", 10,
"George Orwell", "Animal farm");
Book animalFarm2 = new Book("BK001", "Novel", 10,
"George Orwell", "Animal farm");
System.out.println(animalFarm1.equals(animalFarm2));
animalFarm1 = new Book("BK001", "Novel", 10,
"George Orwell", "Animal farm");
animalFarm2 = new Book("BK002", "Novel", 10,
"George Orwell", "Animal farm");
System.out.println(animalFarm1.equals(animalFarm2));
Camera canon1 = new Camera("CA001", "Canon Camera", 230, 16);
Camera canon2 = new Camera("CA001", "Canon Camera", 230, 16);
System.out.println(canon1.equals(canon2));
canon1 = new Camera("CA001", "Canon Camera", 230, 16);
canon2 = new Camera("CA002", "Canon Camera", 230, 16); true
System.out.println(canon1.equals(canon2)); (output) false
true
false - 80 -
Exercise (7): Object class
•Implement equals() and
hashCode() in all
classes…

- 81 -
Exercise (7): Object class
•… such that following code in the main class produces
the output (see below)
Rectangle rect1 = new Rectangle(4, 5, 10, 20);
Rectangle rect2 = new Rectangle(4, 5, 10, 20);
System.out.println(rect1.equals(rect2));
rect1 = new Rectangle(4, 5, 10, 20);
rect2 = new Rectangle(5, 5, 10, 20);
System.out.println(rect1.equals(rect2));

Circle circ1 = new Circle(4, 5, 10);


Circle circ2 = new Circle(4, 5, 10);
System.out.println(circ1.equals(circ2));
circ1 = new Circle(4, 5, 10);
circ2 = new Circle(5, 5, 10);
System.out.println(circ1.equals(circ2)); true
(output) false
true
false

- 82 -
10.2-10.3

Polymorphism

83
What is Polymorphism?
•Polymorphism (Greek, meaning many forms)
•Inheritance opens the door to polymorphism
thanks to an important property of Java:
A variable of a subclass can be assigned
to a variable of a superclass
Book animalFarm = new Book(…);
Product product1 = animalFarm;
superclass reference subclass reference

// or, shorter syntax


Product product2 = new Book(…);

In other words: a reference of a superclass


can refer to an object of a subclass
- 84 -
Object type casting: FYI
•This property of the Java language manifests itself
when assigning references of related classes,
subclass to superclass, and is known as implicit
upcasting (up the UML class hierarchy)

•What actually happens during assignment:


Book animalFarm = new Book(…);
Product product1 = (Book)animalFarm;
Reference variables animalFarm and Explicit type casting
product1 refer to the same Book-object
The explicit type casting
notation is not necessary
though, since the compiler
executes the assignment
implicitly

- 85 -
Useful consequence 1
•It allows you to treat different objects uniformly
public static void main(String[] args) { No need to create separate
Product[] products = new Product[5]; lists of Book, or Camera, or…
products[0] = new Book("BK001", "Allegorical novel“
, 10, "George Orwell", "Animal farm");
products[1] = new Camera("CA001", "Canon 100 Reflex Camera", 230, 16);
products[2] = new Shirt("SH001", "MEXX T-shirt", 14.99, "Large", "Man");
showInfo(products);
} // main() implicit upcasting

showInfo() treats different objects uniformly


private static void showInfo(Product[] products) { Polymorph method call
for (Product product : products) {
if (product != null) {
System.out.printf("vat=%.2f \n", product.getVat());
}
} // for vat=0.06
} // showInfo() vat=0.21
vat=0.21

- 86 -
Polymorphism: how does it work?

private static void showInfo(Product[] products) {


for (Product product : products) {
if (product != null) {
System.out.printf("vat=%.2f \n", product.getVat());
}
} // for
} // showInfo()

•When calling product.getVat(), will Java use the


method from
– the variable declaration type (compile time type): Product?
– the object the variable refers to (run time type): Book,
Camera, Shirt?
→ If several options are still available at compile time,
then the compiler will not choose and let the decision
take place at runtime

- 87 -
Polymorphism: how does it work?

private static void showInfo(Product[] products) {


for (Product product : products) {
if (product != null) {
System.out.printf("vat=%.2f \n", product.getVat());
}
} // for
} // showInfo()

• At runtime, when the program is executed, reference


variable ‘product’ is examined to determine to what object
it is referring:
– 1st for-loop iteration: product refers to a Book
→ getVat() of class Book is executed: returns 0.06
– 2nd for-loop iteration: product refers to a Camera
→ getVat() of class Camera is executed : returns 0.21
– etc…
getVat() can have many behaviors depending on the
content of product 🡪 polymorphism - 88 -
Polymorphism: how does it work?
•Determining which method to call can happen
– At compile time: called early binding
▪ Faster than late binding
– At runtime: called late binding
▪ Slower than early binding

•“If several options are still available at compile


time, then the compiler will not choose…”
– How to eliminate several options?
▪ If a method does not really need to be overridden,
make sure it can’t be overridden
▪ How?
o Define the method as private or final
- 89 -
Useful consequence 2
•Suppose you want to use a new class:
public class Laptop extends Product {…} getVat() returns 0.21

•Some existing code does not need to be changed!


public static void main(String[] args) {
Product[] products = new Product[5];
products[0] = new Book("BK001", "Allegorical novel“
, 10, "George Orwell", "Animal farm");
products[1] = new Camera("CA001", "Canon 100 Reflex Camera", 230, 16);
products[2] = new Shirt("SH001", "MEXX T-shirt", 14.99, "Large", "Man");
products[3] = new Laptop("LP001", "Laptop", 529, "HP Pavillon");
showInfo(products);
} // main() No need to change showInfo
private static void showInfo(Product[] products) {
for (Product product : products) {
if (product != null) {
System.out.printf("vat=%.2f \n", product.getVat());
}
vat=0.06
} // for vat=0.21
} // showInfo() vat=0.21
vat=0.21
- 90 -
Quiz
1. Classes Convertible and Break are subclasses of
Car. Each class contains a showInfo() method.
Whose method is called in this code?
Car car= new Convertible(); Convertible
car.showInfo();

2. Fish is the superclass of Shark.Which expressions


are correct?
Fish fish = new Shark(); Correct
Shark shark = new Shark(); Fish fish = shark; Correct
Fish fish = new Shark(); Shark shark = (Shark)fish; Correct
Fish fish = new Fish(); Shark shark = fish; Wrong

- 91 -
Try it out (8): Polymorphism
•Add methods showInfo and getTotalPrice in the main
class, in order to have following code produce the
output (see below)
Product[] products = new Product[5];
products[0] = new Book("BK001", "Allegorical novel", 10
, "George Orwell", "Animal farm");
products[1] = new Camera("CA001", "Canon 100 Reflex Camera", 230
, 16);
products[2] = new Shirt("SH001", "MEXX T-shirt", 14.99
, "Large", "Man");

showInfo(products);

double totalPrice = getTotalPrice(products);


System.out.printf("Total price = %.2f Eur (VAT excl.) \n“
, totalPrice);
Allegorical novel : 10.00 Eur (VAT excl.)
(output) Canon 100 Reflex Camera : 230.00 Eur (VAT excl.)
MEXX T-shirt : 14.99 Eur (VAT excl.)
Total price = 254.99 Eur (VAT excl.)
- 92 -
Exercise (8): Polymorphism
•Add methods showInfo and getTotalArea in the main
class, in order to have following code produce the
output (see below)
Shape[] shapes = new Shape[5];
shapes[0] = new Rectangle(4, 5, 10, 20);
shapes[1] = new Circle(4, 5, 10);
shapes[2] = new Circle(7, 8, 20);

showInfo(shapes);

double totalArea = getTotalArea(shapes);


System.out.printf("Total area = %.3f \n\n", totalArea);
Rectangle : 200.000
(output) Circle : 314.159
Circle : 1256.637
Total area = 1770.796

- 93 -
Inheritance Summary
– A way to reuse state and behaviour
– Extends an existing class
– A class can only extend one class directly
→ single inheritance
– Subclass
▪ Is more specific than its superclass (specialisation)
▪ Can do everything its superclass does
▪ Can do more than its superclass does
▪ Can itself be a superclass (tree)
– The class hierarchy (root) starts at java.lang.Object

- 94 -
Exercises
•Ex 07.04 – Ex 07.05

- 95 -
9.7

Inheritance versus
aggregation

96
- 96 -
Inheritance versus aggregation
WHOLE
• Aggregation:
– Een object is a part of another object. PART
– relation: " … has a …"

• Inheritance:
– Een object is a specialisation of another object. PARENT
– relation: " … is a kind of …"

CHILD

- 97 -
Quiz
WHOLE
• Quiz: Aggregation or inheritance?
– Lettuce– Vegetable PART
– Boat - Hull
– Polygon – Hexagon
– Mars - Solar System
– Barman - Bar PARENT

CHILD

- 98 -
Quiz
WHOLE
• Quiz: Aggregation or inheritance?
– Lettuce– Vegetable PART
– Boat - Hull
– Polygon – Hexagon
– Mars - Solar System
– Barman - Bar PARENT

CHILD

- 99 -
Inheritance Aggregation

Is a kind of Has a

public class Animal { public class Phone {


String name; String brand;

public Animal(String name) { public Phone(String brand) {


this.name = name; this.brand = brand;
} }
} }

public class Dog extends Animal{ public class Person {


int chipNumber; char gender;
Phone mobile;

public Dog(String name, public Person(char gender,


int chipNumber) { Phone mobile) {
super(name); this.gender = gender;
this.chipNumber = chipNumber; this.mobile = mobile;
} }
} }

- 100 -
Inheritance Aggregation

Is a kind of Has a

Dog snoopy=new Dog("Snoopy", Person charlie = new Person('M',


1563); new Phone("Motorola"));

1 object
2 objects

Composition
- 101 -
Exercises
•Remaining exercises

- 102 -
Exercises
•Remaining exercises

- 103 -
Review
1. Superclass and subclass
2. Inheritance and accessibility
3. Inheriting attributes
4. Inheriting methods
5. Constructors and inheritance
6. Abstract classes
7. The Object class
8. Polymorphism
9. Inheritance vs Aggregation

- 104 -

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy