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

05 Inheritance

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)
9 views

05 Inheritance

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/ 28

Inheritance & Polymorphism

Object-Oriented Programming
Outline
■ What is inheritance?
■ HAS_A and IS_A relationship
■ Polymorphism
■ Rules for overriding
■ Object class
■ Construction of subclass’ objects

■ Readings: HFJ: Ch.7 Better Living in Objectville

Đại học Công nghệ - ĐHQG HN More on Java 2


What is inheritance

Inheritance and Polymorphism 3


Warning

■ Inheritance is a powerful technology

■ It’s a common OOdesign mistake Person


to apply inheritance to everything.
In most cases,
aggregation/association
is the better choice. Student Lecturer

■ Inheritance is great
when it is applied correctly.
But that’s somewhat rare

Inheritance and Polymorphism 4


Warning

■ Inheritance is a powerful technology

■ It’s a common OOdesign mistake


to apply inheritance to everything.
In most cases,
aggregation/association
is the better choice.

■ Inheritance is great
when it is applied correctly.
But that’s somewhat rare

Inheritance and Polymorphism 5


What is inheritance?

■ The subclass inherits from the superclass,


i.e, the subclass inherits members of the superclass:
❑ instance variables and methods

■ The subclass specializes the superclass:


❑ it can add new variables and methods.

❑ it can override inherited methods.

Đại học Công nghệ - ĐHQG HN Inheritance 6


Example

add a new instance


variable

add a new method

override
the inherited method

Đại học Công nghệ - ĐHQG HN Inheritance 7


class Animal {
String name;
void makeNoise() {
System.out.print("Hmm");
}
} the overriden method

class Cow extends Animal {


boolean givesMilk;
void makeNoise() {
System.out.print("Moooooooo...");
}
}
newly added members
class Dog extends Animal {
void chaseCats() { Cow cow = new Cow();
System.out.print("I'm coming, cat!"); cow.makeNoise();
} cow.givesMilk = true;
} the inherited method
Dog dog = new Dog();
dog.makeNoise();
dog.chaseCats();
Đại học Công nghệ - ĐHQG HN Inheritance 8
IS-A and HAS-A relationship

■ Triangle IS-A Shape ■ House HAS-A Kitchen


■ Cow IS-An Animal ■ Kitchen HAS-A Sink
■ Dog IS-An Animal ■ Kitchen HAS-A Stove

Inheritance Composition

Đại học Công nghệ - ĐHQG HN Inheritance 9


Code reuse

■ Copy & paste


❑ Manually ->Error-prone

■ Composition – “HAS-A” relationship


❑ the new class is composed of objects of existing classes.

❑ reuse the functionality of the existing class, not its form

■ Inheritance – “IS-A” relationship


❑ create a new class as a type of an existing class

❑ new class absorbs the existing class's members and

extends them with new or modified capabilities

Đại học Công nghệ - ĐHQG HN Inheritance 10


What does inheritance buy you?

1. You avoid duplicate code


❑ Common features are put in one place
2. You define a common protocol for a group of
classes
❑ Objects of a subclass are guaranteed to have all
features of the superclass.
❑ Objects of a subclass can be treated as if they
are objects of the superclass.
❑ Polymorphism!

Đại học Công nghệ - ĐHQG HN Inheritance 11


Polymorphism

■ Normally,
Dog myDog = new Dog();

■ With polymorphism:
Animal myDog = new Dog();

The reference type can


be a superclass of
the actual object type.

Đại học Công nghệ - ĐHQG HN Inheritance 12


Polymorphic arrays

■ An array is declared of type Animal. It can hold


objects of Animal's subclasses.

Animal[] animals = new Animal[5]; we put objects of any subclasses of Animal in


the Animal array
animals[0] = new Dog();
animals[1] = new Cat();
animals[2] = new Wolf(); we can loop through the array and
animals[3] = new Hippo(); call Animal-class methods, and
animals[4] = new Lion(); every object does the right thing!

for (int i = 0; i < animals.length; i++) {


animals[i].makeNoise();
} the cat runs Cat's version of makeNoise(),
the dog runs Dog's version,…

Đại học Công nghệ - ĐHQG HN Inheritance 13


Polymorphic arguments and return types

■ Parameters of type Animal can take arguments of


any subclasses of Animal.
class Vet {
public void giveShot(Animal a) { it takes arguments of types Dog and Cat
// give a a shot, vaccination for example
a.makeNoise();
}
} Vet v = new Vet();
Dog d = new Dog();
Cat c = new Cat();
v.giveShot(d);
v.giveShot(c); the Dog's makeNoise() is invoked

the Cat's makeNoise() is invoked

Đại học Công nghệ - ĐHQG HN Inheritance 14


class Animal {
String name;
...
public void makeNoise() { Polymorphism: The same message
System.out.print ("Hmm."); "makeNoise" is interpreted differently,
} depending on the type of the owner object
public void introduce() {
makeNoise();
System.out.println(" I'm " + name);
}
Animal pet1 = new Cat("Tom Cat");
}
Animal pet2 = new Cow("Mini Cow");
class Cat extends Animal {
pet1.introduce();
...
pet2.introduce();
public void makeNoise() {
System.out.print("Meow...");
}
} Meow... I'm Tom Cat
class Cow extends Animal {
Moo... I'm Mini Cow
...
public void makeNoise() {
System.out.print("Moo...");
}
}
Đại học Công nghệ - ĐHQG HN Inheritance 15
What is polymorphism?

■ Polymorphism: exist in many forms


■ Object polymorphism:
❑ Objects of subclasses can be treated as if they
are all objects of the superclass.
■ A Dog object can be seen as an Animal object as well
❑ Even when treated uniformly, objects of different
subclasses interpret the same message differently
■ anAnimal.makeNoise() works differently depending on
what kind of Animal anAnimal is currently refering to.

Đại học Công nghệ - ĐHQG HN Inheritance 16


What polymorphism buy you?

■ With polymorphism, you can write code that doesn't


have to change when you introduce new subclass
types into the program
Animal[] animals = new Animal[5];
...
for (int i = 0; i < animals.length; i++) {
animals[i].makeNoise();
}
class Vet {
public void giveShot(Animal a) {
// give a a shot, vaccination for example
a.makeNoise();
}
}
Đại học Công nghệ - ĐHQG HN Inheritance 17
class Animal {
...
Animal
public void makeNoise() {
System.out.print ("Hmm."); - name
} + makeNoise()
public void introduce() { + introduce()
makeNoise();
System.out.println(" I'm " + name);
}
} Cat Cow Duck

class Pig extends Animal {


public void makeNoise() { + makeNoise() + makeNoise() + makeNoise()
System.out.print("Oi oi...");
}
} class Duck extends Animal {
public void makeNoise() {
System.out.print("Quack quack...");
}
}
You can add as many new animal types as you want
without having to modify the introduce() method !

Separate things that change from things that stay the same

Đại học Công nghệ - ĐHQG HN Inheritance 18


protected access level

Modifier accessible within


same class same subclasses universe
package
private Yes
package (default) Yes Yes
protected Yes Yes Yes
public Yes Yes Yes Yes

Đại học Công nghệ - ĐHQG HN Inheritance 19


protected access level
■ protected members of a superclass are directly
accessible from inside its subclasses.
public class Person {
protected String name;
Subclass can directly access
protected String birthday; superclass‘s protected members
...
} public class Employee extends Person {
protected int salary;
public String toString() {
String s;
s = name + "," + birthday;
s += "," + salary;
return s;
}
}

Đại học Công nghệ. ĐHQG Hà Nội Inheritance 20


Rules for overriding

■ The principle: the subclass must be able to do anything the


superclass declares
■ Therefore,
❑ Parameter types must be the same

■ whatever the superclass takes as an argument, the subclass


overriding the method must be able to take that same
argument.
❑ Return types must be compatible
■ whatever the superclass declares as return type, the subclass
must return the same type or a subclass type.
❑ The method can't be less accessible
■ a public method cannot be overriden by a private version

Đại học Công nghệ - ĐHQG HN Inheritance 21


Wrong overriding

Đại học Công nghệ - ĐHQG HN Inheritance 22


Object class

■ All classes are subclasses to the class Object


■ inherited methods:
■ Class getClass()
■ int hashCode()
■ boolean equals(Object)
hashCode(), equals() and
■ String toString() toString() should be overriden
to work properly
Car c1 = new Car();
Car c2 = new Car();

System.out.println(c1.equals(c2));
System.out.println(c1.getClass() + c1.hashCode());
System.out.println(c1.toString() + "," + c2);

Đại học Công nghệ - ĐHQG HN Inheritance 23


equals(Object object)
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)
Remember!
public boolean equals(Object other) { parameter type must be Object
if (other == this) return true;
if (other == null) return false;
if (other.getClass() != this.getClass()) return false;
PhoneNumber that = (PhoneNumber) other;
return (this.area == that.area) &&
(this.exch == that.exch) && (this.ext == that.ext);
}

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)

public String toString() {


// 0 for padding with digits with leading 0s
return String.format("(%03d) %03d-%04d", area, exch, ext);
}

System.out.println("a = " + a);

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

Must override in order to use as key type for java.util.HashSet or java.util.HashMap

Reading: https://algs4.cs.princeton.edu/34hash/

26
Each object has
everything from its superclass

27
Constructor Chaining

28

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