Inheritance
Object-oriented programming
Outline
What is inheritance? Inheritance in Java Reuse
Readings:
Java how to program, chapter 9
i h c Cng ngh . HQG H N i
Inheritance
"is-a" relationship
Similar things (sharing same set of attributes/operations) a group / a concept
Student
Person
Employee
Full-time Student Part-time Student Manager
Similar groups (sharing a subset of attributes/operations) a bigger group / a more general concept
A student is a person An employee is a person A manager is an employee
An object of the subgroup "is-a" object of the supergroup
i h c Cng ngh . HQG H N i
Inheritance
Inheritance
Based on "is-a" relationship Objects of subclass also belongs to superclass Subclass: more specialized, superclass: more general Subclass is derived or inherits from superclass
hence, the terms 'derived class' and 'base class'
Person name birthday getName()
Employee name birthday getName() salary getSalary()
In essence:
1. 2.
Objects in the same class have the same set of attributes (different values though) and operations 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 Cng ngh . HQG H N i
Inheritance
Inheritance
Person - name: String - birthday: Date + getName(): String
Arrow points from subclass to superclass
An Employee is a Person,
Employee
- salary: double apart from its own members, + 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 Cng ngh . HQG H N i
Inheritance
Person
Inheritance
- name: String - birthday: Date + getName(): String
Student
Employee - salary: double + getSalary(): double
Inheritance tree can have many levels
A Manager object inherits what an Employee has, including what a Person has.
- id: String
Manager - assistant: Employee + setAssistant()
Only new attributes/operations are listed, inherited attributes/operations are not listed in the subclass's box
i h c Cng ngh . HQG H N i Inheritance 6
Inheritance in Java
How to? 1. Subclass extends superclass
New attributes/operations Redefine inherited operations
Method overriding
Person - name: String - birthDate: Date + getName(): String
Employee - salary: double + getSalary(): double
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 Cng ngh . HQG H N i Inheritance 7
New attributes/operations
Syntax:
[public] class Subclass extends Superclass { /* new features go here */ }
Person - name: String - birthDate: Date + getName(): String
Example:
class Employee extends Person { private double salary; public boolean setSalary(double sal) { ... salary = sal; return true; } }
i h c Cng ngh . HQG H N i Inheritance
Employee - salary: double + getSalary(): double
New attributes/operations
public class Person { private String name; private Date birthday; public boolean setName(String n) { name = n; return true; } public String getName() { return name; } } } public class Employee extends Person { private double salary; public boolean setSalary(double s) { salary = s; return true; } public double getSalary() { return salary; }
//application code ... Employee e = new Employee(); [Link]("John"); [Link]([Link]()); [Link](3.0);
i h c Cng ngh . HQG H N i
calls to Persons methods from an Employee object
calls to Employees method from an Employee object
9
Inheritance
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
Superclasss methods of the same name can be reused by using the keyword super
i h c Cng ngh . HQG H N i
Inheritance
10
Method overriding - Example
Subclass's version does something else
class Animal { String name; public void sayHello() { [Link] ("Huh?"); } }
Define a new version of the inherited sayHello()
class Cow extends Animal { public void sayHello() { [Link] ("Mooo..."); } } //client code Animal a1 = new Animal("Bob"); [Link](); Cow c1 = new Cow("Alice"); [Link](); Animal a2 = c1; [Link]();
i h c Cng ngh . HQG H N i Inheritance
Which version gets to run? It depends on which class the object belongs to. NOT the class the reference belongs to C:\java>java WhoGetsToRun Huh? Mooo... Mooo...
11
More example
Subclass's version calls superclass's version then does something extra
Call method of the superclass from within the subclass. Keyword super is the public class Person { 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 Cng 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 Cng 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 Employees code is not affected.
Hiding does not mean preventing source code from being seen by programmers.
i h c Cng ngh . HQG H N i
Inheritance
14
Access control levels
Modifier same class private package (default) protected public Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes accessible within same package subclasses universe
i h c Cng ngh . HQG H N i
Inheritance
15
protected access level
protected members of a superclass are directly accessible from inside its subclasses.
public class Person { protected String name; protected Date birthday; ... } Subclass can directly access superclasss protected members
public class Employee extends Person { ... public String toString() { String s; s = name + "," + birthday; //no error. s += "," + salary; return s; } }
i h c Cng 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 accessed directly from within the same package public class Person { 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 Cng ngh . HQG H N i Inheritance 17
In different packages
Members with package access level cannot be accessed directly by subclasses from outside the package package people; public class Person { 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 Cng ngh . HQG H N i Inheritance 18
In different packages
Members with protected access level can be accessed directly by subclasses from outside the package package people; public class Person { 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 Cng 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 librarys classes Inherit classes from third-party vendors
Inherit without knowing source code
Protect source code Increase reusability
i h c Cng ngh . HQG H N i
Inheritance
20
Constructor of subclass
Subclass inherits all attributes/ 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. 2.
(Implicit) use default constructors Explicit calls to constructors of the baseclass
i h c Cng 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; } } class Circle extends Point { protected int radius; public Circle() {} }
Default constructor Point() is called
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 Cng 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 Cng 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; } } //application code Point p = new Point(10, 10); Circle c1 = new Circle(); Circle c2 = new Circle(10, 10, 5); //
Explicit calls to Point(int, int)
ok
i h c Cng 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; public Circle() {} 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);
Error! Default constructor Point() is not found
i h c Cng 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 Cng ngh . HQG H N i
Inheritance
26
Multiple level inheritance
Person -name -birthday +setName +setBirthday
All classes inherits from class Object
Employee -salary +setSalary +getDetail
Student -id ...
Manager -rank ...
Programmer -project ...
i h c Cng 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 Cng 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 Cng ngh . HQG H N i
Inheritance
29
final keyword
final attribute
Constant value, assigned value once upon initialisationa 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 Cng ngh . HQG H N i
Inheritance
30
final arguments
class MyDate { int year, month, day; public MyDate(int y, int year = y; month = m; } public void copyTo(final [Link] = year; [Link] = month; [Link] = day; d = new MyDate(year, } ... } m, int d) { day = d; MyDate d) {
month, day); //error
i h c Cng 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 Cng ngh . HQG H N i
Inheritance
32
Reusing classes - composition
Existing class is used as a component of the new class Reused features might need new interface
Interface must be rewritten when necessary Not flexible enough in some cases
getName must be rewritten as a wrapper Person - name: String - birthday: Date + Person() + getName(): String Date - day: int - month: int - year: int + Date() + nextDate(): Date + toString(): String
Employee - myself : Person - salary: double + Employee() + getName(): String + getSalary(): double
Person - name: String - birthday: Date + Person() + getName(): String
i h c Cng ngh . HQG H N i
Inheritance
33
Manager - myself : Employee - assistant: Employee + getName(): String + setAssistant()
Employee - myself : Person - salary: double + getName(): String + getSalary(): double
Person - name: String - birthday: Date + getName(): String
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; } ... Inflexible! Assistant cant be a Manager } //application code ... Manager junior = new Manager(); Manager senior = new Manager(); [Link](junior); // error
i h c Cng ngh . HQG H N i Inheritance 34
Reusing classes inheritance
i h c Cng ngh . N i
HQG H Inheritance
Manager - assistant: Employee + setAssistant() class Person { private String name; private Date birthday; public String getName() { return name; } ... } class Employee extends Person { private double salary; ... }
Employee - salary: double + getSalary(): double
Person - name: String - birthday: Date + getName(): String
class Manager extends Employee { private Employee assistant; public setAssistant(Employee e) { assistant = e; } ... } Yes! Assistant can be a manager //application code ... Manager junior = new Manager(); Manager senior = new Manager(); [Link](junior); // no error
i h c Cng ngh . HQG H N i Inheritance 36