Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

Inheritance in Java

Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the mechanism in


java by which one class is allowed to inherit the features(fields and methods) of another class. 

Inheritance in Java: Why do we need it?


 Code Reusability: The code written in the Superclass is common to all subclasses.
Child classes can directly use the parent class code.
 Method Overriding: Method Overriding is achievable only through Inheritance. It
is one of the ways by which java achieves Run Time Polymorphism.
 Abstraction: The concept of abstract where we do not have to provide all details is
achieved through inheritance. Abstraction only shows the functionality to the user.

Important terminology: 
 Super Class: The class whose features are inherited is known as superclass(or 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.
How to use inheritance in Java
The keyword used for inheritance is extends. 
Syntax : 
class derived-class extends base-class
{
//methods and fields
}
class Teacher {
String designation = "Teacher";
String collegeName = "Beginners College";
void does(){
System.out.println("Teaching");
}
}

class PhysicsTeacher extends Teacher


{
String mainSubject = "Physics";
public static void main()
{
PhysicsTeacher obj = new PhysicsTeacher();
System.out.println(obj.collegeName);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
}
}
Output:

Beginners college
Teacher
Physics
Teaching
Based on the above example we can say that PhysicsTeacher IS-A Teacher. This means
that a child class has IS-A relationship with the parent class. This is inheritance is known
as IS-A relationship between child and parent class

Note:
The derived class inherits all the members and methods that are declared as public or
protected. If the members or methods of super class are declared as private then the
derived class cannot use them directly. The private members can be accessed only in its
own class. Such private members can only be accessed using public or protected getter
and setter methods of super class as shown in the example below.

class Teacher {
private String designation = "Teacher";
private String collegeName = "Beginnersbook";
public String getDesignation() {
return designation;
}
protected void setDesignation(String designation) {
this.designation = designation;
}
protected String getCollegeName() {
return collegeName;
}
protected void setCollegeName(String collegeName) {
this.collegeName = collegeName;
}
void does(){
System.out.println("Teaching");
}
}

public class JavaExample extends Teacher{


String mainSubject = "Physics";
public static void main(String args[]){
JavaExample obj = new JavaExample();
/* Note: we are not accessing the data members
* directly we are using public getter method
* to access the private members of parent class
*/
System.out.println(obj.getCollegeName());
System.out.println(obj.getDesignation());
System.out.println(obj.mainSubject);
obj.does();
}
}
The output is:
Beginnersbook
Teacher
Physics
Teaching
The important point to note in the above example is that the child class is able to access
the private members of parent class through protected methods of parent class. When we
make a instance variable(data member) or method protected, this means that they are
accessible only in the class itself and in child class. 

In practice, inheritance and polymorphism are used together in java to achieve fast performance and
readability of code.
class Calculation {
int z;

public void addition(int x, int y) {


z = x + y;
System.out.println("The sum of the given numbers:"+z);
}

public void Subtraction(int x, int y) {


z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}

class MyCalculation extends Calculation {


public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}

public static void main(String args[]) {


int a = 20, b = 10;
MyCalculation demo = new MyCalculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}

Output
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200
In the given program, when an object to My_Calculation class is created, a copy of the contents
of the superclass is made within it. That is why, using the object of the subclass you can access
the members of a superclass.
is-a relationship
In Java, inheritance is an is-a relationship. That is, we use inheritance only if there
exists an is-a relationship between two classes. For example,
 Car is a Vehicle
 Orange is a Fruit
 Surgeon is a Doctor
 Dog is an Animal
Here, Car can inherit from Vehicle, Orange can inherit from Fruit, and so on.

Types of inheritance
There are five types of inheritance.

1. Single Inheritance

In single inheritance, a single subclass extends from a single superclass. For example,

Java Single Inheritance


2. Multilevel Inheritance

In multilevel inheritance, a subclass extends from a superclass and then the same
subclass acts as a superclass for another class. For example,

Java Multilevel Inheritance

3. Hierarchical Inheritance

In hierarchical inheritance, multiple subclasses extend from a single superclass. For


example,
Java Hierarchical Inheritance

4. Multiple Inheritance

In multiple inheritance, a single subclass extends from multiple superclasses. For


example,

Java Multiple Inheritance

Note: Java doesn't support multiple inheritance. However, we can achieve multiple
inheritance using interfaces.
5. Hybrid Inheritance

Hybrid inheritance is a combination of two or more types of inheritance. For example,

Java Hybrid Inheritance

Here, we have combined hierarchical and multiple inheritance to form a hybrid


inheritance.

Types of Inheritance in Java


Below are the different types of inheritance which are supported by Java. 
1. Single Inheritance: In single inheritance, subclasses inherit the features of one superclass. In the
image below, class A serves as a base class for the derived class B.
// Java program to illustrate the
// concept of single inheritance
import java.io.*;
import java.lang.*;
import java.util.*;
 
class one {
    public void print_one()
    {
        System.out.println("One");
    }
}
 
class two extends one {
    public void print_two() { System.out.println("Two"); }
}
// Driver class
public class Main {
    public static void main()
    {
        two ob = new two();
        ob.print_one();
        ob.print_two();
        ob.print_one();
    }
}

Output
One
Two
One

2. Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base class
and as well as the derived class also act as the base class to other class. In the below image, class A
serves as a base class for the derived class B, which in turn serves as a base class for the derived
class C. In Java, a class cannot directly access the grandparent’s members.
// Java program to illustrate the
// concept of Multilevel inheritance

 
class one {
    public void print()
    {
        System.out.println("ISC");
    }
}
 
class two extends one {
    public void print_for() { System.out.println("Computer"); }
}
 
class three extends two {
    public void print2()
    {
        System.out.println("Science");
    }
}
 
// Driver class
class Main {
    public static void main()
    {
        three ob = new three();
        ob.print();
        ob.print_for();
        ob.print2();
    }
}

Output
ISC
Computer
Science

3. Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base


class) for more than one subclass. In the below image, class A serves as a base class for the derived
class B, C and D.
// Java program to illustrate the
// concept of Hierarchical  inheritance
 
class A {
    public void print_A()
{ System.out.println("Class A");
}
}
 
class B extends A {
    public void print_B() { System.out.println("Class B"); }
}
 
class C extends A {
    public void print_C() { System.out.println("Class C"); }
}
 
class D extends A {
    public void print_D() { System.out.println("Class D"); }
}
 
// Driver Class
public class Test {
    public static void main()
    {
        B obj_B = new B();
        obj_B.print_A();
        obj_B.print_B();
 
        C obj_C = new C();
        obj_C.print_A();
        obj_C.print_C();
 
        D obj_D = new D();
        obj_D.print_A();
        obj_D.print_D();
    }
}

Output
Class A
Class B
Class A
Class C
Class A
Class D
Hierarchical Inheritance

 
4. Multiple Inheritance (Through Interfaces): In Multiple inheritances, one class can have more
than one superclass and inherit features from all parent classes. Please note that Java
does not support multiple inheritances with classes. In java, we can achieve multiple inheritances
only through Interfaces. In the image below, Class C is derived from interface A and B.
// Java program to illustrate the
// concept of Multiple inheritance
import java.io.*;
import java.lang.*;
import java.util.*;
 
interface one {
    public void print_1();
}
 
interface two {
    public void print_2();
}
 

class child implements one,two {


    @Override public void print_1()
    {
        System.out.println("Computer Science");
    }
 
    public void print_2() { System.out.println("with Java"); }
}
 
// Driver class
public class Main {
    public static void main()
    {
        child c = new child();
        c.print_1();
        c.print_2();
       }
}

Output
Computer Science
With Java

5. Hybrid Inheritance(Through Interfaces): It is a mix of two or more of the above types of


inheritance. Since java doesn’t support multiple inheritances with classes, hybrid inheritance is also
not possible with classes. In java, we can achieve hybrid inheritance only through Interfaces.
 

Important facts about inheritance in Java 



 Superclass can only be one: A superclass can have any number of subclasses. But
a subclass can have only one superclass. This is because Java does not
support multiple inheritances with classes. Although with interfaces, multiple
inheritances are supported by java.
 Inheriting Constructors: A subclass inherits all the members (fields, methods, and
nested classes) from its superclass. Constructors are not members, so they are not
inherited by subclasses, but the constructor of the superclass can be invoked from
the subclass.
 Private member inheritance: A subclass does not inherit the private members of
its parent class. However, if the superclass has public or protected methods(like
getters and setters) for accessing its private fields, these can also be used by the
subclass.

What all can be done in a Subclass?


In sub-classes we can inherit members as is, replace them, hide them, or supplement them with new
members: 
 The inherited fields can be used directly, just like any other fields.
 We can declare new fields in the subclass that are not in the superclass.
 The inherited methods can be used directly as they are.
 We can write a new instance method in the subclass that has the same signature as
the one in the superclass, thus overriding it (as in the example
above, toString() method is overridden).
 We can write a new static method in the subclass that has the same signature as the
one in the superclass, thus hiding it.
 We can declare new methods in the subclass that are not in the superclass.
 We can write a subclass constructor that invokes the constructor of the superclass,
either implicitly or by using the keyword super.

Inheritance and Method Overriding


When we declare the same method in child class which is already present in the parent
class then this is called method overriding. In this case when we call the method from
child class object, the child class version of the method is called. However we can call the
parent class method using super keyword as shown in the example below:

class ParentClass{
//Parent class constructor
ParentClass(){
System.out.println("Constructor of Parent");
}
void disp(){
System.out.println("Parent Method");
}
}
class JavaExample extends ParentClass{
JavaExample(){
System.out.println("Constructor of Child");
}
void disp(){
System.out.println("Child Method");
//Calling the disp() method of parent class
super.disp();
}
public static void main(){
//Creating the object of child class
JavaExample obj = new JavaExample();
obj.disp();
}
}
The output is :

Constructor of Parent
Constructor of Child
Child Method
Parent Method

 Following figure shows the four classes in this example and how they are related.

Classes and Packages of the Example Used to Illustrate Access Levels

The following table shows where the members of the Alpha class are visible for each of the access modifiers that can be
applied to them.

Visibility
Modifier Alpha Beta Alphasub Gamma
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

Java language has four access modifier to control access level for classes and
its members.

 Default: Default has scope only inside the same package

 Public: Public has scope that is visible everywhere

 Protected: Protected has scope within the package and all sub classes

 Private: Private has scope only within the classes


Java also supports many non-access modifiers, such as static, abstract,
synchronized, native, volatile, transient etc. We will cover these in our other
tutorial.

You might also like