Chapter 5-3 OOP Inheritance Part 3
Chapter 5-3 OOP Inheritance Part 3
Objectives
To define the syntax of inheritance
in Java
To understand the class hierarchy of
Java
To understand the concept of
polymorphism
2
Terminology
Inheritance is a fundamental
Object Oriented concept
subclass: Employee
- employeeID: int
- salary: int
The subclass can - startDate: Date
Override
Add new Use inherited
inherited
functionality functionality
functionality
What really happens?
Person Person
- name: String name = "John Smith"
- dob: Date dob = Jan 13, 1954
Employee
name = "Sally Halls"
is a kind of
dob = Mar 15, 1968
Employee employeeID = 37518
- employeeID: int salary = 65000
- salary: int startDate = Dec 15,
- startDate: Date 2000
Inheritance in Java
Inheritance is declared using the "extends" keyword
If inheritance is not defined, the class extends a class called Object
}
11
Object References and
Inheritance
Inheritance defines • In the previous example,
"a kind of" OverdraftAccount "is a kind of"
relationship. BankAccount
Because of this
• A superclass reference can refer to
relationship,
an instance of the superclass OR an
programmers can
instance of ANY class which inherits
"substitute"
from the superclass.
object references.
Object References and
Inheritance
BankAccount anAccount = new BankAccount(123456, "Craig");
BankAccount
anAccount name = "Craig"
accountNumber = 123456
OverdraftAccount
name = "John"
accountNumber = 3323
account1 12
limit = 1000.0
Polymorphism
In the previous slide, the two variables
are defined to have the same type at
compile time: BankAccount
The types of objects they are
referring to at runtime are
different
13
Polymorphism
WHAT HAPPENS WHEN THE
WITHDRAW METHOD IS INVOKED ON
EACH OBJECT?
anAccount refers
to an instance of
account1 refers to
an instance of
The method being
BankAccount OverdraftAccount. invoked on an object
is determined AT
withdraw method withdraw method RUNTIME and is
defined in
BankAccount is
defined in
OverdraftAccount based on the type of
invoked. is invoked.
the object receiving
the message.
13
Polymorphism
• means "many forms", and it occurs
when we have many classes that
Polymorphism
are related to each other by
inheritance.
14
METHODS OF OBJECT CLASS
Method Description
public int hashCode() Returns the hashcode number for this object.
18
E X A M P L E TOSTRING ()
class Student {
int rollno;
String name;
String city;
Output:
Student(int rollno, String name, String city) {
this.rollno = rollno; 101 Jo hn L A
this.name = name; 101 Jo hn L A
this.city = city;
}
19
THE EQUALS() METHOD
20
EXAPME OF THE EQUALS METHOD
22
Final Methods and Final
Classes
Methods can be qualified with the Classes can be qualified with the
final modifier final modifier
Final methods cannot be The class cannot be extended
overridden.
This can be useful for security
purposes.
23