Inheritance
Object-oriented programming
Outline
What is inheritance?
Inheritance in Java
Reuse
Readings:
Java how to program, chapter 9
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 2
"is-a" relationship Computer
Similar things (sharing same set of PDA Laptop
attributes/operations)
a group / a concept Smartphone
Motorola A910 is a smartphone
Nokia E72 is a smartphone
Nokia E72 Motorola A910 LenovoG450
Lenovo G450 is a laptop
Similar groups (sharing a subset of attributes/operations)
a bigger group / a more general concept
A smartphone "is a" PDA (Personal Digital Assistant)
A PDA "is a" computer
A laptop "is a" computer
An object of the subgroup "is-a" object of the supergroup
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 3
Inheritance Person
name
birthday
getName()
Based on "is-a" relationship
Objects of subclass also belongs to superclass
Subclass: more specialized, superclass: more general Employee
Subclass is derived or inherits from superclass name
birthday
hence, the terms 'derived class' and 'base class' getName()
In essence: salary
getSalary()
1. Objects in the same class have the same set of
attributes (different values though) and operations
2. Objects of subclass have all members of superclass plus some more
Objects of a subclass can also be treated as objects of its superclass
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 4
Person
Inheritance
Arrow points
- name: String
- birthday: Date
from
+ getName(): String subclass to
… superclass
An Employee “is a” Person, Employee
apart from its own members, - salary: double
+ getSalary(): double
salary and getSalary, …
it also has name, birthday,
getName() without having
to declare them
Employee is the subclass (derived) of Person
Person is the superclass (base) of Employee
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 5
Person
Inheritance
- name: String
- birthday: Date
+ getName(): String
…
Employee
- salary: double
Student + getSalary(): double
- id: String …
Inheritance tree can have …
many levels Manager
A Manager object inherits - assistant: Employee
+ setAssistant()
what an Employee has, …
including what a Person
has.
Only new attributes/operations are listed,
inherited attributes/operations are not
listed in the subclass's box
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 6
Inheritance in Java Person
- name: String
- birthDate: Date
+ getName(): String
…
How to? Employee
1. Subclass “extends” superclass - salary: double
+ getSalary(): double
New attributes/operations …
Redefine inherited operations
Method overriding
2. Treat subclass objects as superclass
objects
Access inherited data members and
methods
Information hiding
Initialise inherited data members
using constructor of superclass
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 7
New attributes/operations
Syntax:
[public] class Subclass extends Superclass {
Person
/* new features go here */ - name: String
- birthDate: Date
}
+ getName(): String
…
Example: Employee
class Employee extends Person { - salary: double
private double salary; + getSalary(): double
…
public boolean setSalary(double sal) {
...
salary = sal;
return true;
}
}
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 8
New attributes/operations
public class Person { public class Employee extends Person {
private String name; private double salary;
private Date birthday;
public boolean setSalary(double s) {
public boolean setName(String n) { salary = s;
name = n; return true; return true;
} }
public String getName() { public double getSalary() {
return name; return salary;
} }
} }
//application code calls to Person’s methods from an Employee object
...
Employee e = new Employee();
[Link]("John");
[Link]([Link]());
[Link](3.0); calls to Employee’s method from an Employee object
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 9
Method overriding
A subclass can redefine methods inherited from
its superclass.
To specialise these methods to suit the new problem
Objects of the subclass will work with the new
version of the methods
Dynamic binding
Superclass’s methods of the same name can be
reused by using the keyword super
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 10
Method overriding - Example
Subclass's version does something else
class Animal {
String name;
public void sayHello() { Define a new version of the inherited sayHello()
[Link] ("Uh oh!");
}
}
Which version gets to run?
class Cow extends Animal {
public void sayHello() { It depends on which class the
[Link] ("Mooo..."); object belongs to. NOT the class
} the reference belongs to
} //client code
Animal a1 = new Animal("Bob");
C:\java>java WhoGetsToRun
[Link]();
Cow c1 = new Cow("Alice"); Uh oh!
[Link]();
Mooo...
Animal a2 = c1;
[Link](); Mooo...
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 11
More example
Subclass's version calls superclass's version
then does something extra
Call method of the superclass
from within the subclass.
public class Person { Keyword super is the
reference to the superclass
protected String name;
protected Date birthday;
public void display() {
[Link] (name + "," + birthday);
}
...
public class Employee extends Person {
}
...
public void display() {
[Link]();
[Link] ("," + salary);
}
}
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 12
Method overriding - Rules
New and old version must have the same
prototype:
Same return type
Same argument type
Private methods cannot be overriden
Private members are hidden from subclass
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 13
Superclass information hiding
Superclass programmer and subclass programmer might not be the
same person.
Simple reuse independent of specific implementations
Employee does not have to care how name and birthday are stored
and processed inside Person but can still use them
Internal design and implementation of superclass can be modified
without requiring changes in subclasses
e.g, class Person could have three int attributes instead of one Date
attribute for birthday, or two instead of one String for name. Class
Employee’s code is not affected.
Hiding does not mean preventing source code from being seen by
programmers.
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 14
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 Date birthday; superclass‘s protected members
...
}
public class Employee extends Person {
...
public String toString() {
String s;
s = name + "," + birthday; //no error.
s += "," + salary;
return s;
}
}
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 15
Access control levels
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 Hà Nội Inheritance 16
In the same package
package people;
Default access level is “package”, which means
those with “package” access level can be public class Person {
accessed directly from within the same package String name;
Date birthday;
...
package people; }
public class Employee extends Person {
...
public String toString() {
String s;
s = name + "," + birthday; //no error.
s += "," + salary;
return s;
}
}
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 17
In different packages
package people;
Members with “package” access level
cannot be accessed directly by public class Person {
subclasses from outside the package String name;
Date birthday;
…
import [Link]; }
public class Employee extends Person {
...
public String toString() {
String s;
s = name + "," + birthday; //Error.
s += "," + salary;
return s;
}
}
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 18
In different packages
package people;
Members with “protected” access level
can be accessed directly by public class Person {
subclasses from outside the package protected String name;
protected Date birthday;
…
import [Link]; }
public class Employee extends Person {
...
public String toString() {
String s;
s = name + "," + birthday; //no error.
s += "," + salary;
return s;
}
}
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 19
Inherit from another package
Can create subclass of a class from a
different package
Inherit from Java standard library’s classes
Inherit classes from third-party vendors
Inherit without knowing source code
Protect source code
Increase reusability
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 20
Constructor of subclass
Subclass inherits all atttibutes/ methods of
superclass
Subclass must initialize inherited members
But, constructors are NOT inherited
syntactically, they have different names
Two ways to call constructors of the baseclass
1. (Implicit) use default constructors
2. Explicit calls to constructors of the baseclass
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 21
class Point {
protected int x, y;
public Point() {}
public Point(int xx, int yy) {
x = xx;
y = yy;
} Default constructor Point() is called
}
class Circle extends Point {
protected int radius;
public Circle() {}
}
Cannot found Circle(int, int).
Point(int, int) is not inherited
//client code
Point p = new Point(10, 10);
Circle c1 = new Circle();
Circle c2 = new Circle(10, 10); // error
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 22
Calling constructors of baseclass
The initializing baseclass' attributes should
be carried out by baseclass' constructors
Why?
Baseclass' constructors can be called
using reference super
Baseclass' constructors must run first
If baseclass has no default constructor then
its constructor must be called explicitly
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 23
class Point {
protected int x, y;
public Point() {}
public Point(int xx, int yy) {
x = xx;
y = yy;
}
}
class Circle extends Point {
protected int radius;
public Circle() { super(0, 0); }
public Circle(int xx, int yy, int r) {
super(xx, yy);
radius = r; Explicit calls to
} Point(int, int)
}
//application code
Point p = new Point(10, 10);
Circle c1 = new Circle();
Circle c2 = new Circle(10, 10, 5); // ok
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 24
class Point {
protected int x, y;
public Point(int xx, int yy) {
x = xx;
y = yy;
}
}
class Circle extends Point {
protected int radius; Error! Default constructor Point()
public Circle() {} is not found
public Circle(int xx, int yy, int r) {
radius = r;
}
}
//application code
Point p = new Point(10, 10);
Circle c1 = new Circle();
Circle c2 = new Circle(10, 10, 5);
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 25
Constructors - order of execution
class Point {
protected int x, y;
public Point() {
[Link]("Point constructor");
}
}
class Circle extends Point {
protected int radius;
public Circle() {
[Link]("Circle constructor");
}
}
//application code
Circle c1 = new Circle();
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 26
Multiple level inheritance
Person
-name All classes inherits from class Object
-birthday
+setName
+setBirthday
Student
Employee -id
-salary ...
+setSalary
+getDetail
Programmer
Manager
-project
-rank
...
...
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 27
toString() method
Inherits from Object class
class Point {
protected int x, y;
public String toString() {
return "<" + x + "," + y + ">";
}
} Overriding Object's toString()
New versions are used in
class Circle extends Point {
[Link]()
protected int radius;
public String toString() {
return [Link] + "," + radius;
}
}
//application code
Circle c = new Circle();
[Link](c);
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 28
Basic data wrapper types
Object
Boolean Character Void Number Math String StringBuffer ..
.
Byte Short Integer Long Float Double
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 29
final keyword
final attribute
Constant value, assigned value once upon initialisation…a final
attribute cannot be changed
final method
Cannot be overriden in subclasses
final arguments
Method cannot change value of final arguments/parameters
final class
Cannot create subclasses of a final class
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 30
final arguments
class MyDate {
int year, month, day;
public MyDate(int y, int m, int d) {
year = y; month = m; day = d;
}
public void copyTo(final MyDate d) {
[Link] = year;
[Link] = month;
[Link] = day;
d = new MyDate(year, month, day); //error
}
...
}
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 31
Reusing Classes
Object classes with similar or related attributes and behaviour
Person, Student, Manager,…
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 Hà Nội Inheritance 32
Reusing classes - composition
Person
Existing class is used as
- name: String
a component of the new - birthday: Date
class + Person()
+ getName(): String
Date
Reused features might - day: int
need new interface - month: int
- year: int
Interface must be rewritten + Date()
+ nextDate(): Date
when necessary + toString(): String
Not flexible enough in
some cases Employee Person
- name: String
- birthday: Date
getName must be - myself : Person
rewritten as a wrapper - salary: double
+ Employee()
+ getName(): String
+ getSalary(): double + Person()
…
Inheritance
+ getName(): String
33
Đại học Công nghệ. ĐHQG Hà Nội
Manager Employee Person
- myself : Employee - myself : Person - name: String
- assistant: Employee - salary: double - birthday: Date
+ getName(): String + getName(): String + getName(): String
+ setAssistant() + getSalary(): double …
… …
class Person {
private String name; getName must be rewritten as wrappers
private Date birthday;
public String getName() { return name; }
...
} class Employee {
private Person myself;
private double salary;
public String getName() { return [Link](); }
...
} class Manager {
private Employee myself;
private Employee assistant;
public String getName() { return [Link](); }
public setAssistant(Employee e) { assistant = e; }
...
} //application code Inflexible! Assistant can’t be a Manager
...
Manager junior = new Manager();
Manager senior = new Manager();
[Link](junior); // error
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 34
Reusing classes - inheritance
Đại học Công nghệ.
ĐHQG Hà Nội Inheritance
Manager Employee
Person
- assistant: Employee - salary: double
- name: String
- birthday: Date
class Person { + setAssistant() + getSalary(): double
… …
private String name; + getName(): String
private Date birthday; …
public String getName() { return name; }
...
} class Employee extends Person {
private double salary;
...
}
class Manager extends Employee {
private Employee assistant;
public setAssistant(Employee e) { assistant = e; }
...
}
//application code Yes! Assistant can be a manager
...
Manager junior = new Manager();
Manager senior = new Manager();
[Link](junior); // no error
Đại học Công nghệ. ĐHQG Hà Nội Inheritance 36