INHERITANCE AND POLYMORPHISM
IN JAVA
Object-Oriented Programming
www.beginwithjava.com
WHAT YOU SHOULD LEARN
What Is Inheritance?
Calling the Superclass Constructor
Overriding Methods
Protected Member
Multilevel Inheritance
Polymorphism
Abstract Classes and Abstract Method
Interfaces
www.beginwithjava.com
WHAT IS INHERITANCE
Inheritance is the mechanism that allows
programmers to create new classes from existing
class. By using inheritance programmers can re-use
code they've already written.
Any new class that you create from an existing
class is called sub class; existing class is
called super class.
www.beginwithjava.com
www.beginwithjava.com
The sub class gets all of the methods and state variables of the super
class by default.
The sub class can add new methods and state variables.
The complete program of above diagram is available at : www.beginwithjava.com
CALLING THE SUPER CLASS CONSTRUCTOR
A subclass can have its own private data members,
so a subclass can also have its own constructors.
The constructors of the subclass can initialize only
the instance variables of the subclass.
When a subclass object is instantiated the subclass
object must also automatically execute one of the
constructors of the super class.
To call a super class constructor the super keyword
is used.
www.beginwithjava.com
The complete example program is available at : www.beginwithjava.com
OVERRIDING SUPER CLASS METHODS
In a class hierarchy, when a method in a subclass
has the same name and type signature as a method
in its super class, then the method in the subclass
is said to override the method in the super class.
The version of the method defined by the super
class will be hidden inside subclass.
www.beginwithjava.com
The complete example program is available at : www.beginwithjava.com
PROTECTED MEMBER
The private members of a class cannot be directly
accessed outside the class. Only methods of that class
can access the private members directly.
However, sometimes it may be necessary for a subclass
to access a private member of a super class.
If you make a private member public, then anyone can
access that member. So, if a member of a super class
needs to be (directly) accessed in a subclass and yet still
prevent its direct access outside the class, you must
declare that member protected.
Modifier
public
protected
private
Class
Y
Y
Y
www.beginwithjava.com
Subclass
Y
Y
N
World
Y
N
N
continue.
Visit www.beginwithjava.com