Vous êtes sur la page 1sur 14

Inheritance in Java

Inheritance in java is a mechanism in which one object( child class) acquires all the properties and
behaviors of parent object(parent class).
Inheritance allows a class to use the properties and methods of another class. In other words, the
derived class inherits the states and behaviors from the base class. The derived class is also called
subclass and the base class is also known as super-class. The derived class can add its own additional
variables and methods. These additional variable and methods differentiates the derived class from the base
class.
Inheritance is a compile-time mechanism. A super-class can have any number of subclasses. But a
subclass can have only one superclass. This is because Java does not support multiple inheritance.
The idea behind inheritance in java is that you can create new classes that are built upon existing classes.
When you inherit from an existing class, you can reuse methods and fields of parent class, and you
can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance in java?
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
Syntax of Java Inheritance :
class <Subclass-name> extends <Superclass-name>
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing class.
In the terminology of Java, a class that is inherited is called a Super class. The new class is called a Subclass.
Understanding the simple example of inheritance

Super class

Sub class

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. It means
Programmer class (Sub Class ) inherits all properties of Employee Class (Super class)
class 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("Bonus of Programmer is:"+p.bonus);
}
}

Output

Programmer salary is: 40000.0


Bonus of Programmer is: 10000
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn
about interfaces later.

Note: Multiple inheritance is not supported in java through class.


When a class extends multiple classes i.e. known as multiple inheritance. For Example:

Difference between Java Inheritance and C++ Inheritance


The main difference between java Inheritance and C++ Inheritance is; Java doesnt support multiple
inheritance but C++ support.

Here is the complete example:


// A class to display the attributes of the vehicle
class Vehicle
{
String color;
int speed;
int size;
void attributes()
{
System.out.println("Color : " + color);
System.out.println("Speed : " + speed);
System.out.println("Size : " + size);
}
}
/* A subclass which extends for vehicle */
class Car extends Vehicle
{
int CC;
int gears;
void attributescar()
{
// The subclass refers to the members of the superclass
System.out.println("Color of Car : " + color);
System.out.println("Speed of Car : " + speed);
System.out.println("Size of Car : " + size);
System.out.println("CC of Car : " + CC);
System.out.println("No of gears of Car : " + gears);
}
}
public class Test
{
public static void main(String args[])
{
Car b1 = new Car();
b1.color = "Blue";
b1.speed = 200 ;
b1.size = 22;
b1.CC = 1000;
b1.gears = 5;
b1.attributescar();
}
}
The output is
Color of Car : Blue
Speed of Car : 200
Size of Car : 22
CC of Car : 1000
No of gears of Car : 5
The derived class inherits all the members and methods that are declared as public or protected .
If declared as private it cannot be inherited by the derived classes. The private members can be
accessed only in its own class. The private members can be accessed through assessor methods as
shown in the example below.
The derived class cannot inherit a member of the base class if the derived class declares another
member with the same name.

// A class to display the attributes of the vehicle


class Vehicle
{
String color;
private int speed;
private int size;
public int getSize() /* Public method which can access private data inside same class */
{
return size; /*Accessing private member through method Inside same class */
}
public int getSpeed()
{
return speed; /*Accessing private member through method Inside same class */
}
public void setSize(int i)
{
size = i; /*Accessing private member through method Inside same class */
}
public void setSpeed(int i)
{
speed = i;
}
}
/*A subclass which extends for vehicle */
class Car extends Vehicle
{
int CC;
int gears;
int color;
void attributescar()
{
// Error due to access violation
// System.out.println("Speed of Car : " + speed);
// Error due to access violation
//System.out.println("Size of Car : " + size);
}
}
public class Test
{
public static void main(String args[])
{
Car b1 = new Car();
b1.color = 500; /* the subclass can inherit 'color' member of the superclass as it is not private */
b1.setSpeed(200) ;
b1.setSize(22);
b1.CC = 1000;
b1.gears = 5;
// The subclass refers to the members of the superclass
System.out.println("Color of Car : " + b1.color);
System.out.println("Speed of Car : " + b1.getSpeed());
System.out.println("Size of Car : " + b1.getSize());
System.out.println("CC of Car : " + b1.CC);
System.out.println("No of gears of Car : " + b1.gears);
}
}

The output is:


Color of Car : 500
Speed of Car : 200
Size of Car : 22
CC of Car : 1000
No of gears of Car : 5

1) Single Inheritance
Single inheritance is damn easy to understand. When a class extends another one class only then we call
it a single inheritance. The below flow diagram shows that class B extends only one class which is A. Here A
is a parent class of B and B would be a child class of A.
Single Inheritance example program in Java
Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}
2) Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a derived
class, thereby making this derived class the base class for the new class.
As you can see in below flow diagram C is subclass or child class of B and B is a child class of A.

Multilevel-Inheritance
Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}

3)

Hierarchical Inheritance in Java with Example

In this inheritance multiple classes inherit from a single class i.e there is one super class and multiple
sub classes. As we can see from the below diagram when a same class is having more than one sub class (or)
more than one sub class has the same parent is called as Hierarchical Inheritance.

Here ClassA acts as the parent for sub classes ClassB, ClassC and ClassD. Lets take a look into the
below code.

public class ClassA


{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassA
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
}
public class ClassD extends ClassA
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
}
public class HierarchicalInheritanceTest
{
public static void main(String args[])
{
ClassB b = new ClassB();
/* Assigning Clild class ClassB object to ClassB reference */
b.dispB();
/* Call dispB() method of ClassB */
b.dispA();
/* Call dispA() method of parent class ClassA */
ClassC c = new ClassC();
c.dispC();
c.dispA();

/* Assigning ClassC object to ClassC reference */


/* Call dispC() method of ClassC */
/* Call dispA() method of ClassA */

ClassD d = new ClassD();


d.dispD();
d.dispA();

/* Assigning ClassD object to ClassD reference */


/* Call dispD() method of ClassD */
/* Call dispA() method of ClassA */

}
}
Output :
disp() method of ClassB
disp() method of ClassA
disp() method of ClassC
disp() method of ClassA
disp() method of ClassD
disp() method of ClassA

Q) Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes
have same method and you call it from child class object, there will be ambiguity to call method of A or B
class.
Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2
classes. So whether you have same method or different, there will be compile time error now.
class A
{
void msg()
{
System.out.println("Hello");
}
}
class B
{
void msg()
{
System.out.println("Welcome");
}
}
class C extends A,B //suppose if it were
{
Public Static void main(String args[])
{
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Test it Now
Compile Time Error
Important Points for Inheritance:
1. In java programming one derived class can extends only one base class because java programming
does not support multiple inheritance through the concept of classes, but it can be supported
through the concept of Interface.
2. Whenever we develop any inheritance, application first creates an object of bottom most derived
class but not for top most base class.
3. When we create an object of bottom most derived class, first we get the memory space for the data
members of top most base class, and then we get the memory space for data member of other
bottom most derived class.
4. Bottom most derived class contains logical appearance for the data members of all top most base
classes.
5. If we do not want to give the features of base class to the derived class then the definition of the base
class must be preceded by final hence final base classes are not reusable or not inheritable.
6. If we are do not want to give some of the features of base class to derived class than such features of base
class must be as private hence private features of base class are not inheritable or accessible in derived
class. It is only accessible in base class only.
7. Data members and methods of a base class can be inherited into the derived class but constructors
of base class can not be inherited because every constructor of a class is made for initializing its own
data members but not made for initializing the data members of other classes.
8. An object of base class can contain details about features of same class but an object of base class
never contains the details about special features of its derived class (this concept is known as scope
of base class object).
9. For each and every class in java there exists an implicit predefined super class called java.lang.Object.
because it providers garbage collection facilities to its sub classes for collecting un-used memory space
and improved the performance of java application.

IS-A Relationship
IS-A is a way of saying: This object is a type of that object. Let us see how the extends keyword is used to
achieve inheritance.
public class Animal
{
}
public class Mammal extends Animal
{
}
public class Reptile extends Animal
{
}
public class Dog extends Mammal
{
}
Now, based on the above example, in Object-Oriented terms, the following are true
Animal is the superclass of Mammal class.
Animal is the superclass of Reptile class.
Mammal and Reptile are subclasses of Animal class.
Dog is the subclass of both Mammal and Animal classes.
Now, if we consider the IS-A relationship, we can say
Mammal IS-A Animal
Reptile IS-A Animal
Dog IS-A Mammal
Hence: Dog IS-A Animal as well
With the use of the extends keyword, the subclasses will be able to inherit all the properties of the superclass
except for the private properties of the superclass.
We can assure that Mammal is actually an Animal with the use of the instance operator.
class Animal
{
}
class Mammal extends Animal
{
}
class Reptile extends Animal
{
}
public class Dog extends Mammal
{
public static void main(String args[])
{
Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}
Output
true
true
true

Since we have a good understanding of the extends keyword, let us look into how the implements keyword is
used to get the IS-A relationship.
Generally, the implements keyword is used with classes to inherit the properties of an interface. Interfaces
can never be extended by a class.
public interface Animal {
}
public class Mammal implements Animal {
}
public class Dog extends Mammal {
}

The instanceof Keyword


Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog is
actually an Animal.
class Animal{}
class Mammal extends Animal{}
public class Dog extends Mammal
{
public static void main(String args[])
{
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}
Output
true
true
true

HAS-A relationship
These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain
thing. This relationship helps to reduce duplication of code as well as bugs.
Lets look into an example
Example
public class Vehicle{}
public class Speed{}
public class Van extends Vehicle {
private Speed sp;
}
This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the entire
code that belongs to speed inside the Van class, which makes it possible to reuse the Speed class in multiple
applications.
In Object-Oriented feature, the users do not need to bother about which object is doing the real work. To
achieve this, the Van class hides the implementation details from the users of the Van class. So, basically what
happens is the users would ask the Van class to do a certain action and the Van class will either do the work
by itself or ask another class to perform the action.

Constructor calling in inheritance


In case Of inheritance Super class default constructor is called implicitly when programmer creats the Child
class object through by calling the child Class constructor through a new operater
class parent1
{
parent1()
/* Parent class Default Constructor /*
{
System.out.println("\n Inside Parent class Default Constructure");
}
}
class child1 extends parent1
{
child1()
/* Child Class default Constructor */
{
System.out.println("\n Inside Child Class default Constructure");
}
child1(int i)
/* Child Class parametrised Constructor */
{
System.out.println("\n Inside Child Class Parameterised constructure");
System.out.println("\n child class passed value i" +i);
}
}
class conStructor1
{
public static void main(String args[])
{
int k=45;
child1 ch = new child1(k);
child1 ch1= new child1();
}
}
Output
Inside Parent class Default Constructure
Inside Child Class Parameterised constructure
child class passed value i45
Inside Parent class Default Constructure
Inside Child Class default Constructure
Explanation

Test cases
If parent class parameterized constructor is defined but default constructor is not defined , and child class
object is created through new operator , it will creat a compile time error
class x
{
x(int i)
{
System.out.println("Inside Parent class default class Constructor");
}
}
class y extends x
{
y()
{
System.out.println("Inside child Class parameterised Constructor");
}
}
class new1
{
public static void main(String args[])
{
y ob1=new y();
}
}
Output
new1.java:11: cannot find symbol
symbol : constructor x()
location: class x
{
^
1 error
Similarly, If parent class parameterized constructor is defined but default constructor is not defined , and
child class object is created through new operator , it will creat a compile time error
class x
{
x(int i)
{
System.out.println("Inside Parent class default class Constructor");
}
}
class y extends x
{
y(int i)
{
System.out.println("Inside child Class parameterised Constructor");
}
}
class new1
{
public static void main(String args[])
{
y ob1=new y(12);
}
}

Output
new1.java:11: cannot find symbol
symbol : constructor x()
location: class x
{
^
1 error
If the Child Class parameterized constructor is called , the parent class default class constror is also called
implicitly at that time .
class x
{
x()
{
System.out.println("Inside Parent class default class Constructor");
}
}
class y extends x
{
y(int i)
{
System.out.println("Inside child Class parameterised Constructor");
}
}
class new1
{
public static void main(String args[])
{
y ob1=new y(12);
}
}
Output
Inside Parent class default class Constructor
Inside child Class parameterised Constructor
If super class default constructure is not defined but parameterized constructor is there, then inside child
class constructor (default / paramerised)call the parent class parameterized constructor using super
keyword .
Condition: Super should be first statement in constructor.
Ex1
class x
{
x(int i)
{
System.out.println("Inside Parent class default class Constructor");
}
}
class y extends x
{
y(int i)
{
super(13)003B
System.out.println("Inside child Class parameterised Constructor");
}

}
class new1
{
public static void main(String args[])
{
y ob1=new y(12);
}
}
Output
Inside Parent class default class Constructor
Inside child Class parameterised Constructor
Ex2
class x
{
x(int i)
{
System.out.println("Inside Parent class default class Constructor");
}
}
class y extends x
{
y()
{
super(13);
System.out.println("Inside child Class parameterised Constructor");
}
}
class new1
{
public static void main(String args[])
{
y ob1=new y();
}
}

Inside Parent class default class Constructor


Inside child Class parameterised Constructor
What we learn?
When child class constructor called (whether default or paramerised), base class default
constructor will be called implicitly. If base class default constructor is not defined then it will
generate compile time time error.
Even if pamaterised constructor is defined but default constructor is not metioned in parent
class , When child class constructor called (whether default or paramerised)it will still
generate compile time error.
If we dont want to mentioned default constructor , then define paramerised constructor then
call it inside child class constructor (either default or paramerised ).

Vous aimerez peut-être aussi