04 - Inheritance
04 - Inheritance
Objectives
• Study concepts: superclass, subclass
• Understand the “is-a” relationship
• Functions in inheritance
• Using an “instanceof” operator
Implementing
Object-Oriented Relationships
• 3 common relations in classes:
– “is a/ a kind of”
– “has a”
– association
• Examples:
– Student is a person
– “A home is a house that has a family and a
pet.”
– An invoice contains some products and a
product can be contained in some invoices
Implementing
Object-Oriented Relationships…
The relation “is a” is Person The relation “has a”
implemented as a
- String name, address is implemented as
sub-class - String birthDate reference
Classes Professor, + String getName();
Student are sub-classes + void setName(String n);
of the class Person …….
Sub-classes inherit the
structure of super class
is a is a
Professor Student
- String department - String studentId, majorField
+ String getDepartment(); teach - String degreeSought
+ void setDepartment(String d); + String getStudentId();
+ void setStudentID(String id)
….
6
Inheritance
• Hence, to make them work, we customised these
inherited methods – this is called overriding
Student.java
/***************** Overriding methods ******************/
@Override
public String toString() {
return "Student{" + "code=" + code + ", name=" + name
+ ", bYear=" + bYear + ", address=" + address + '}';
}}
7
Inheritance
• Object-oriented languages allow inheritance
• Declare a new class based on an existing class
• So that the new class may inherit all of the attributes
and methods from the other class
• Terminology
• If class B is derived from class A, then class B is called
a child (or subclass or derived class) of class A
• Class A is called a parent (or superclass) of class B
8
Inheritance
• Have the Person class
Person.java
class Person {
private String name;
private String address;
private String birthDate;
public String getName() { ... }
public vois setName(String name) {... }
public void eat() { ... }
public void toString() { ... }
}
9
Inheritance
• Let’s define a Professor class
• Basic information:
• Person name, address, birthDate
• Interest department
New requirements
• Basic functionality:
• eat
• instruct interest
• Compare with the basic Person:
• Differences are highlighted above
• Professor shares more than 50% of the code with Person
• So, should we just cut and paste the code from Person to
create Professor?
10
Inheritance
• Duplicating code is undesirable as it is hard to
maintain
• Need to correct all copies if errors are found
• Need to update all copies if modifications are required
• Since the classes are logically unrelated if the
codes are separated:
• Code that works on one class cannot work on the other
• Compilation errors due to incompatible data types
• Hence, we should create Person as a subclass of
Professor
11
Inheritance
Person.java
class Person { The “protected” keyword
protected String name; allows subclass to access
protected String address; the attributes directly
protected String birthDate
//Constructors and methods not shown
}
The “extends”
class Professor extends Person { keyword indicates
inheritance
protected String department;//interest department
+ getDepartment() + getName()
+ setDepartment() + setName()
+ instruct() + eat()
13
Inheritance
• Inheritance greatly reduces the amount of
redundant coding
• In Professor class,
• No definition of name, address, birthDate
• No definition of eat
• Improve maintainability:
• Eg: If a method is modified in Persion class, no
changes are needed in Professor class
• The code in Persion remains untouched
• Other programs that depend on Persion are unaffected
very important!
14
Inheritance
• An added advantage for inheritance is that:
• Whenever a super class object is expected, a sub class
object is acceptable as substitution!
• Caution: the reverse is NOT true (Eg: A cat is an
animal; but an animal may not be a cat.)
• Hence, all existing functions that works with the super
class objects will work on subclass objects with no
modification!
• Analogy:
• We can drive a car
• Honda is a car (Honda is a subclass of car)
• We can drive a Honda
15
The “Object” Class
• In Java, all classes are descendants of a
predefined class called Object
• Object class specifies some basic behaviors common
to all objects
• Any methods that works with Object reference will
work on object of any class
• Methods defined in the Object class are inherited in
all classes
• Two inherited Object methods are
• toString() method
• equals() method
• However, these inherited methods usually don’t work
because they are not customised
16
“is-a” versus “has-a”
• Words of caution:
• Do not overuse inheritance
• Do not overuse protected
• Make sure it is something inherent for future
subclass
class BankAcct {
...
}; Person BankAcct
class Person {
private BankAcct myAcct;
}; Dotted arrow
Attribute: Person HAS-A BankAcct
18
Inheritance…
• How to construct a class hierarchy? Intersection
Electric Products< code, name, make, price, guaranty, voltage, power>
Ceramic Products < code, name, make, price, type >
Food Products < code, name, make, price , date, expiredDate >
Product
code
name
make
price
Hierarchical Multiple
Inheritance Inheritance
• A parent class has more • A child class
than one child classes at derives from
different levels more than one
parent class
Subclass in Java
• can declare a field with the same name as the one in
the super class hiding of super class field which is
not advisable.
• can declare new fields. These members will be
specific to the subclass an declare new fields
• can write a new instance method with the same
signature as the one in the super class method
overriding.
• can create a new static method with the same
signature as the one in the super class hiding of
the super class method.
• also can declare new methods.
Inheritance…: “super” Keyword
• Constructors Are Not Inherited
• super(...) for Constructor Reuse
• super(arguments); //invoke a superclass
constructor
• The call must be the first statement in the
subclass constructor
• Replacing the Default Parameterless
Constructor
Inheritance…: “super” Keyword
• We use the Java keyword super as the
qualifier for a method call:
super. methodName(arguments);
• Whenever we wish to invoke the version of
method methodName that was defined by
our superclass.
• super() is used to access the superclass's
constructor. And It must be the first
statement in the constructor of the
subclass.
Inheritance…: “final” Keyword
• Sometimes, we want to prevent inheritance by
another class (eg: to prevent a subclass from corrupting the
behaviour of its superclass)
• Use the final keyword
• Eg: final class Person will prevent a subclass to be created
from Person
• Sometimes, we want a class to be inheritable, but
want to prevent some of its methods to be overridden
by its subclass
• Use the final keyword on the particular method:
public final void cry() { … }
will prevent the subclass of Person from overriding cry()
24
Inheritance…
Inheritance…
Overriding and Hiding Methods (1)
• Overriding a method: An instance method in a
subclass with the same signature (name, plus
the number and the type of its parameters) and
return type as an instance method in the
superclass overrides the superclass's method.
• Use the @Override annotation that instructs the
compiler that you intend to override a method in the
superclass (you may not use it because overriding is
the default in Java).
• Hiding a method: Re-implementing a static
method implemented in super class
Overriding and Hiding Methods (2)
Using an “instanceof” operator
• Dynamic and Static type
dynamic type: A reference variable that has the type of the
superclass can store the address of the object of sub class. It is
called to be dynamic type, the type that is has at runtime.
Person obj1 = new Student();
Static type: The type that it has when first declared. Static type
checking is enforced by the compiler.
Student obj2 = new Student();
• “Instanceof” operator: It checks whether the reference
of an object belongs to the provided type or not, the instanceof
operator will return true or false.
If ( obj1 instanceof Student)
System.out.println(“ obj1 is pointing to the Student object”);
Casting
• A variable that has the type of the superclass only calls
methods of the superclass. To call methods of the
subclass we must cast explicitly
• for example,
Person obj = new Student();
((Student)obj).study();
Quick Quiz
A
• Assume all methods print out message of the
form <class name>,<method name> + m()
+ n()
• Eg: method m() in class A prints out “A.m”.
If a class overrides an inherited method, the B C
method’s name will appear in the class icon.
Otherwise, the inherited method remains + n() + m()
+ p()
unchanged in the subclass.
For each code fragment below, indicate whether:
D
The code will cause compilation error, and briefly explain; or
The code can compile and run. Supply the execution result. + m()
+ n()
Code fragment Compilation error? Execution result + p()
(example) Why?
A a = new A(); A.m
a.m();
A a = new A(); Method k() not defined
a.k(); in class A
[501043 Lecture 5: Inheritance]
31
Quick Quiz A
+ m()
+ n()
Code fragment Compilation error? Execution result
B C
A a = new C();
+ n() + m()
a.m(); + p()
B b = new A();
b.n(); D
A a = new B(); + m()
+ n()
a.m(); + p()
A a;
C c = new D();
a = c;
a.n();
B b = new D();
b.p();
C c = new C();
c.n();
A a = new D();
a.p();
32
Test
a) ABC
b) AAC
c) ABA
d) Compile-time
error
a) ABC
b) AAC
c) ABA
d) Compile-time
error
a) ABC
b) AAA
c) ABA
d) None of the
others
AB and a ClassCastException
Test
a) AAA
b) ACB
c) None of the
others
d) ABC
Test
a) ABC
b) AAA
c) ABA
d) None of the
others
Compile-time error
( Type conformity violation)
Test
a) 120
b) 120A
c) None of the
others
d) A120
Test
a) A7500
b) 500A7
c) 500
d) None of the
others
Compile-time error
( static code can not access
instance variables)
Test
a) A1210
b) 10A12
c) 17
d) None of the
others
Compile-time error
( The y variable is out of
scope)
Summary
• Object-oriented languages implement reusability of
coding structure through inheritance
• A derived class does not by default inherit the
constructor of a super class
• Constructors in an inheritance hierarchy execute in order
from the super class to the derived class
• Using the instanceof keyword if we need to check the
type of the reference variable.
• Check the type of the reference variable before casting it
explicitly.