M7 Inheritance
M7 Inheritance
-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
-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
-6-
Why inheritance? Shapes application
-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
-8-
Solution 9.2
-9-
extends
•Inheritance is implemented in Java by using
the extends keyword
superclass
(generalization)
extends class
hierarchy
- 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)
- 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?
- 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
- 25 -
2. Add new attributes
•Subclasses can have additional attributes:
– author
– title
- 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
- 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
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 {
// ... // ...
(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;
}
}
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;
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);
}
}
- 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
- 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)
- 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
- 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
- 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
- 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
- 65 -
Inheritance and variables
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
- 67 -
The instanceof operator
• Tests if an object is an instance of a class
– returns false if object is null
• Example
- 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());
- 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;
(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);
–
}
}
- 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.");
}
- 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));
- 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
- 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
- 86 -
Polymorphism: how does it work?
- 87 -
Polymorphism: how does it work?
- 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);
showInfo(shapes);
- 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
- 100 -
Inheritance Aggregation
Is a kind of Has a
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 -