BSCS 208 - AOOP - Lecture 5a - Single Inheritance
BSCS 208 - AOOP - Lecture 5a - Single Inheritance
Object Oriented
Programming
1
Single Inheritance
The Java model of programming makes
extensive use of Inheritance
Normal inheritance plays two roles in
programming.
• When class B inherits from class A, it “reuses”
all the non-private methods and members of
class A.
• B also becomes a subtype of A.
2
Inheritance Hierarchies
• The standard way of drawing out inheritance
is through a tree-like hierarchy.
• In UML the arrows point from the subclass to
the superclass. This is because the
superclass doesn’t generally know of all of its
subclasses but the subclasses know of the
superclass.
3
Inheritance for Code Reuse
• The first side effect of inheritance is gaining
“copies of” non-private members.
• This means that if A had a public method get()
then B will also have a public method get().
4
Virtual methods
• One of the powers of Java is that you don’t
always have to use the methods defined by
the superclass. You can override them in the
subclass.
• Methods that can be overridden are called
virtual methods. By default all methods in
Java are virtual, which means they can all be
overriden.
5
Inheritance for Subtyping
• Inheritance also provides subtyping. This is
because the subclass has all the public
methods and members of the superclass.
• Formally, when we say that B is a subtype of
A, what we are saying is that any place in the
code where an A is expected, a B can be
used, or a B can always take the place of an
A.
6
Single Inheritance of Classes
• Java only allows single inheritance of classes
i.e. a class can only inherit from one
superclass
• This greatly simplifies code by reducing
ambiguity. C++ has multiple inheritance which
causes one to frequently need to specify
which superclass of a given class a method
should be called through.
7
Inheritance examples
Superclass Subclasses
Student GraduateStudent, UndergraduateStudent
8
Sample UML inheritance
hierarchy