You are on page 1of 19

Java

Inheritance, Polymorphism, super


and final
Inheritance
• A mechanism in which a class acquires properties
and behavior from another class.
• Inheritance means IS-A relationship.
• The keyword used in java is: extends
• The class which is inherited is called base class and
the new class is called derived class.

Note: There is no access modifier used while


inheritance.
Why Inheritance??
• Function Overriding
• Code reusability
Sample Program
Types of Inheritance
Important points to note
• “extends” keyword is used for inheritance.
• Multiple inheritance is not possible in Java
through classes.
• But, multiple inheritance can be done by using
interfaces in java.
Simple Inheritance example
Multilevel Inheritance example
Hierarchical Inheritance example
Aggregation
• When a class contains a reference of another
class, it is called aggregation.
• It is called HAS-A relationship.
• The class containing a reference to other class
is said to have ownership of the other class.
Example
Polymorphism
• Method Overloading: It is an example of compile
time polymorphism, where two or more
functions of the same class have same name but
different function signature.

• Method Overriding: It is an example of run time


polymorphism, where a derived has a same
method as base class.(same name and same
function signature)
Method Overriding example
Rules for overriding methods
• There must be a base class and a derived class
• The function name and function signature
must be same in both the classes.
super keyword
• It is a reference variable which is used to refer
immediate parent class object.
• Whenever you create an object of derived class,
an object of base class is implicitly created
which is referred by super reference variable.
• Basically, super will invoke/access base class
members like: instance variables, methods and
constructors.
Instance
Variable
Method
Constructor
final keyword
• The final keyword is used to restrict the user.
• It can be used with variable, method and class.
• final variable: value cannot be
changed(constant)
• final method: cannot be overriden
• final class: cannot be inherited

You might also like