Feb 16, 2016
INHERITANCE
The word inheritance refers to the act
of inheriting material or immaterial possessions by succession .
materialimmaterial
Inheritance in java
• Inheritance is a basic concept in Object Oriented Programming .• Inheritance in java is a mechanism in which one class of objects acquires all the properties and behaviors of a parent class.• represents the IS-A / HAS-A relationship .
terms
•Superclass/base class/parent class : The class from which another class is derived .
•Subclass/derived class/child class : class that is derived from another class .
syntaxInheritance can be implemented
using the keyword extend .
class subclass_name extends superclass_name { //methods and fields }
superclass : employeesubclass : programmerrelation : IS A
programmer IS A employee .
example
source codeclass employee{ float salary=40000; }
class programmer extends Employee{ int bonus=10000; public static void main(String args[]) { programmer p=new programmer(); system.out.println(“programmer salary is :"+p.salary); system.out.println(“ponus of Programmer is:"+p.bonus); } }
outputprogrammer salary is : 40000.0 bonus of programmer is : 10000
types1.Single
inheritance .2.Multiple
inheritance .3.Multilevel
inheritance .4.Hierarchical inheritance
.5.Hybrid inheritance
.
Single inheritance
A single class is inherited from a single baseclass
example
Multiple inheritanceA single class is
inherited from a more than one baseclasses.
Java does not support multiple inheritance .
That is why java is said to be simple .
Multilevel
inheritance
A derived class acts as baseclass for another class .
example
Hierarchical inheritance
More than one class is inherited from a single baseclass
example
hybrid inheritance
a combination of single and multiple
inheritance
advantages•Code reusability – object of a derived class can also access the field of its base class .•Method overriding – we can define a same method in a derived class without altering the function in base class .