Professional Documents
Culture Documents
Object-oriented programming
Outline
What is inheritance?
Inheritance in Java
Reuse
Readings:
Java how to program, chapter 9
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
Inheritance
Arrow points
- name: String
- birthday: Date
from
+ getName(): String subclass to
… superclass
Inheritance
- name: String
- birthday: Date
+ getName(): String
…
Employee
- salary: double
Student + getSalary(): double
- id: String …
e.setName("John");
System.out.print(e.getName());
e.setSalary(3.0); calls to Employee’s method from an Employee object
class Animal {
String name;
public void sayHello() { Define a new version of the inherited sayHello()
System.out.println ("Uh oh!");
}
}
Which version gets to run?
class Cow extends Animal {
public void sayHello() { It depends on which class the
System.out.println ("Mooo..."); object belongs to. NOT the class
} the reference belongs to
} //client code
Animal a1 = new Animal("Bob");
C:\java>java WhoGetsToRun
a1.sayHello();
Cow c1 = new Cow("Alice"); Uh oh!
c1.sayHello();
Mooo...
Animal a2 = c1;
a2.sayHello(); Mooo...
//application code
Point p = new Point(10, 10);
Circle c1 = new Circle();
Circle c2 = new Circle(10, 10, 5);
//application code
Circle c1 = new Circle();
Student
Employee -id
-salary ...
+setSalary
+getDetail
Programmer
Manager
-project
-rank
...
...
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