(See Person.java)
Output:
A student is a person We can create a Student class by inheri1ng from or extending the Person class In object-oriented programming, inheritance is used to model is-a rela1onships
The constructor of the Student class calls the constructor of its parent class (Person) using the keyword super The Student class overrides the printInfo() method of its parent class The implementa1on of the printInfo() method in the Student class calls the printInfo() method in the parent class
Inheritance
Terminology
Java-specic
terminology
The
Student
class
extends
the
Person
class
Language-independent
terminology
The
Student
class
inherits
from
the
Person
class
The
Person
class
is
the
base
class
/
super
class
/
parent
class
/
ancestor
,
while
the
Student
class
is
the
derived
class
/
subclass
/
descendant
Output:
(See TestStudent2.java)
Output:
Although
the
variable
ko
is
a
Person
reference,
it
actually
points/refers
to
a
Student
object.
This
is
valid
because
Student
is
a
derived
class
of
Person.
The
run1me
engine
is
able
to
gure
out
that
the
printInfo()
method
being
invoked
is
that
of
the
Student
class
(since
the
variable
points
to
a
student
object).
This
is
called
late
binding
in
Java
The
printInfo()
method
of
the
Student
class
in
turn
calls
the
printInfo()
method
of
its
parent
class
(Person)
The
printInfo()
method
of
Person
prints
the
name
and
the
age
The
printInfo()
method
of
Student
then
prints
the
gradua1on
year
and
student
id.
G.
Ayorkor
Korsah,
Ashesi
University
College,
Programming
II
-
First
Semester
2011
8
(See Worker.java)
Just
like
how
we
can
say
a
Student
is
a
Person,
we
can
also
say
a
Worker
is
a
Person
G.
Ayorkor
Korsah,
Ashesi
University
College,
Programming
II
-
First
Semester
2011
9
(See TestPerson2.java)
Note that if we have a variable whose type is a Person reference (like the elements of this array), then we can assign to it not only instances of the Person class, but also instances of any class that extends the Person class (e.g. instances of the Student & Worker classes)
10
11