05 Inheritance
05 Inheritance
Object-Oriented Programming
Outline
■ What is inheritance?
■ HAS_A and IS_A relationship
■ Polymorphism
■ Rules for overriding
■ Object class
■ Construction of subclass’ objects
■ Inheritance is great
when it is applied correctly.
But that’s somewhat rare
■ Inheritance is great
when it is applied correctly.
But that’s somewhat rare
override
the inherited method
Inheritance Composition
■ Normally,
Dog myDog = new Dog();
■ With polymorphism:
Animal myDog = new Dog();
Separate things that change from things that stay the same
System.out.println(c1.equals(c2));
System.out.println(c1.getClass() + c1.hashCode());
System.out.println(c1.toString() + "," + c2);
24
toString()
public final class PhoneNumber {
private final int area; // area @code (3 digits)
private final int exch; // exchange (3 digits)
private final int ext; // extension (4 digits)
25
hashCode()
public final class PhoneNumber {
private final int area; // area @code (3 digits)
private final int exch; // exchange (3 digits)
private final int ext; // extension (4 digits)
should be a small prime number
public int hashCode() {
return 31 * (area + 31 * exch) + ext;
}
Reading: https://algs4.cs.princeton.edu/34hash/
26
Each object has
everything from its superclass
27
Constructor Chaining
28