You are on page 1of 9

What is Inheritance in Java?

Inheritance is an integral part of Java OOPs which lets the properties of


one class be inherited by the other. For example, a child inherits the traits
of his/her parents. Inheritance is a programming construct that software
developers use to establish is-a relationships between categories.

In the Java language, classes can be derived from other classes, thereby
inheriting fields and methods from those classes. Inheritance means
establishing a logical relationship between two classes. In other words,
inheritance means extending class functionalities (code reusing). Here,
Relationship is categorized into two types:

Is-a relationship
Has-a relationship
What is Inheritance in Java

Important Terminology in Inheritance:


Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
Super Class: The class whose features are inherited is known as a
superclass. The class from which the subclass is derived is called a
superclass (also a base class or a parent class).
Sub Class: The class that inherits the other class is known as a subclass(or
a derived class, extended class, or child class). The subclass can add its
own fields and methods in addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we
want to create a new class and there is already a class that includes some
of the code that we want, we can derive our new class from the existing
class. By doing this, we are reusing the fields and methods of the existing
class.
Extends keyword in Java:
In Java, using the “extends” keyword we can implement features
programmatically. The Extends keyword establishes the is-a relationship
between the classes. extends is the keyword used to inherit the properties
of a class.
Syntax:
Extends keyword in Java

In the below code snippet

Example Extends Keyword in Java

Here, class A is known as Base class or superclass, or parent class, and


class B is known as derived/sub/child class. In the above snippet, class B
contains additionally all the members of A (i.e.: because of the is-a
relationship).

Types of Inheritance in Java:


Supported types of Inheritance in Java are as follows:

Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Note: Compared to C++, Java does not support multiple inheritances
directly. Individually, multiple inheritances are supported in Java using the
interface concept.

Why Multiple Inheritance is not supported in Java using classes?


Multiple Inheritance means creating a derived by extending multiple base
classes at a time. Assume in the below code snippet

Why Multiple Inheritance is not supported in Java using classes

In this case, the compiler goes in an ambiguous state, because multiple


base classes contain the same method name. In C++, we can handle this
ambiguous problem using colon (::) operator syntax & syntactically it is not
supported because Java follows a dynamic loading procedure for non-static
members (i.e.: we must use references to access those members)

Single Inheritance in Java:


Single Inheritance means creating a subclass to extend only one
superclass at a time. In the diagram given below, class B inherits class A,
so there is single inheritance.

Single Inheritance in Java

Example of Single Inheritance in Java:


package Demo;
class A
{
int returnSum (int i, int j)
{
return i + j;
}
}
class B extends A
{
void display ()
{
int result = returnSum (10, 20);
System.out.println (result);
}
}
public class SingleInheritance
{
public static void main (String args[])
{
B b1 = new B ();
b1.display ();
b1 = null;
}
}
Output: 30

In Java, whenever in the object creation of subclass, internally. JVM


creates an object of the superclass. Because of tight coupling & JVM
maintains superclass object copy into the subclass object. So once the
subclass object becomes unreachable internally superclass object is also
garbage collected.

In the case of accessing always first priority is given to subclass members


whereas, in the case of object creation, the first priority is given to the
superclass and next to the subclass.

Multilevel Inheritance in Java:


Creating a subclass (derived class) indirectly to the superclass is known as
multilevel inheritance. As you can see below in the diagram, class C
inherits class B which again inherits class A, so there is a multilevel
inheritance.

Multilevel Inheritance in Java

Example of Multilevel Inheritance in Java:


package Demo;
class SampleA
{
void f1 ()
{
System.out.println ("class A f1()");
}
}
class SampleB extends SampleA
{
void f2 ()
{
System.out.println ("class B f2()");
}
}
class SampleC extends SampleB
{
void f3 ()
{
System.out.println ("class C f3()");
}
}
public class MultilevelInheritance
{
public static void main (String srgs[])
{
SampleC a1 = new SampleC ();
a1.f1 ();
a1.f2 ();
a1.f3 ();
a1 = null;
}
}
Output:
class A f1()
class B f2()
class C f3()

Hierarchical Inheritance in Java:


When two or more classes inherit a single class, it is known as hierarchical
inheritance. In the diagram given below, the B and C classes inherit class
A, so there is hierarchical inheritance.
Hierarchical Inheritance in Java
Example of Hierarchical Inheritance in Java:
package Demo;

class one
{
public void print_hello()
{
System.out.println("Hello");
}
}

class two extends one


{
public void print_world()
{
System.out.println("World");
}
}

class three extends one


{
/*............*/
}

// Drived class
public class HierarchicalInheritance
{
public static void main(String[] args)
{
three g = new three();
g.print_hello();
two t = new two();
t.print_world();
g.print_hello();
}
}
Output:
Hello
World
Hello

Super Keyword in Java:


The super keyword is similar to this keyword. The keyword super can be
used to access any data member or method of the parent class. The super
keyword can be used at the variable, method, and constructor levels.
Following are the scenarios where the super keyword is used:

To access the superclass variable from a subclass.


To access the superclass methods from a subclass.
To access the superclass constructor from a subclass.
Syntax of super(): super. <method_name> ();

When and where to call Super()?


Just as this() must be the first element in a constructor that calls another
constructor in the same class, super() must be the first element in a
constructor that calls a constructor in its superclass. If you break this rule
the compiler will report an error. The compiler will also report an error if it
detects a super() call in a method; only ever call super() in a constructor.

Example of Inheritance using Super Keyword in Java:


package Demo;
class Father
{
int bank_balance = 500000;
}

class Daughter extends Father


{
int bank_balance = 300000;
public void displayBalance ()
{
System.out.println ("Bank Balance: " + super.bank_balance);
}
}

public class Inheritance


{
public static void main (String[]args)
{
Daughter d = new Daughter ();
d.displayBalance ();
}
}
Output: Bank Balance: 500000

Can we use the super keyword in the static method?


No, because static methods are loaded as soon as JVM creates a
CONTEXT memory for the subclass but the super keyword is pointed to the
superclass object. In this case, the object is not created so that’s why we
cannot access the super keyword in the static method.

Need for Inheritances in Java:


The most important use is the reusability of code. The code that is present
in the parent class doesn’t need to be written again in the child class. To
achieve runtime polymorphism through method overriding.

What You Can Do in a Subclass?


You can use the inherited members as is, replace them, hide them, or
supplement them with new members:
The inherited fields or methods can be used directly, just like any other
field.
You can declare a field or methods and write a new static method in the
subclass with the same name as the one in the superclass, thus hiding it
(not recommended).
You can declare new fields in the subclass that are not in the superclass.
You can write a new instance method in the subclass that has the same
signature as the one in the superclass, thus overriding it.
You can write a subclass constructor that invokes the constructor of the
superclass, either implicitly or by using the keyword super.
Rules of writing Inheritance in Java:
Multiple Inheritance is NOT permitted in Java using classes.
Cyclic Inheritance is NOT permitted in Java.
Private members do NOT get inherited.
Constructors cannot be Inherited in Java.
In Java, we assign parent references to child objects.
Constructors get executed because of super() present in the constructor.
Advantages of Inheritance in Java:
It reduces duplicate code (i.e.: define ones and use at anywhere(Java
slogan))
It provides code re-usability support.
It increases the maintenance of the Application.
It reduces application development time.

You might also like