x

Java – Inheritance

PREV     NEXT

  • Inheritance is the process of inheriting the attributes (data member) and behaviour (methods) of an existing class into a new class. (i.e. Inheritance is a process in which one class acquires the features of already existing class)
  • The new class which inherits all characteristics of the existing class is called as Sub class.
  • The existing class which is being inherited is called as SuperClass.
  • Inheritance can be achieved by adding ‘extends’ keyword near the sub class name and then followed by the superclass (class which has to be inherited).

Example:


  • The subclass can access the attributes and behaviour of the superclass in addition to its own attributes and behaviour.
  • Consider a class vehicle which has 3 subclasses – car, ship, flight.

Inhertitance Logo


  • The methods start(), stop(), parking() are common to all the vehicles and hence they are added in the vehicle class.
  • The car class contains driving() method and the methods start(), stop(), parking() which are inherited from the vehicle class.
  • Similarly the classes ship and flight have the methods specific to them in addition to the methods inherited from the vehicle class.
  • A class cannot extend more than one class. Multiple inheritance is not allowed in Java unlike in C++. But one super class can have multiple sub class.
Class A extends B, C // not allowed

Class M extends A

Class N extends A

Class O extends A    // class A has 3 subclasses M, N, O

Multi level Inheritance:

A subclass can be inherited by another class.

Example:

Member Access in Inheritance:

A subclass can access all the members of the superclass except those which are declared as private.

Example:

Class A{

private int a1;

int a2;

..}

Class B extends A{

a1=5; //not allowed

a2 = 10;

..}

PREV     NEXT



Like it? Please Spread the word!