0% found this document useful (0 votes)
86 views

Inheritance & Types in Java

Inheritance allows one class to inherit features from another class in Java. The class whose features are inherited is called the superclass, while the class that inherits is called the subclass. The subclass can add its own fields and methods in addition to the inherited fields and methods from the superclass. This supports code reusability, where a new subclass can reuse fields and methods from an existing superclass. There are different types of inheritance in Java including single, multilevel, hierarchical, and multiple inheritance through interfaces.

Uploaded by

mahima yadav
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views

Inheritance & Types in Java

Inheritance allows one class to inherit features from another class in Java. The class whose features are inherited is called the superclass, while the class that inherits is called the subclass. The subclass can add its own fields and methods in addition to the inherited fields and methods from the superclass. This supports code reusability, where a new subclass can reuse fields and methods from an existing superclass. There are different types of inheritance in Java including single, multilevel, hierarchical, and multiple inheritance through interfaces.

Uploaded by

mahima yadav
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Inheritance in Java

Inheritance is an important pillar of OOP(Object Oriented Programming).


It is the mechanism in java by which one class is allow to inherit the
features(fields and methods) of another class.
Important terminology:
 Super Class: The class whose features are inherited is known as
super class(or a base class or a parent class).
 Sub Class: The class that inherits the other class is known as sub
class(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
}
Example: In below example of inheritance, class Bicycle is a base class,
class MountainBike is a derived class which extends Bicycle class and
class Test is a driver class to run program.
filter_none
edit
play_arrow
//Java program to illustrate the 
// concept of inheritance
  
// base class
class Bicycle 
{
    // the Bicycle class has two fields
    public int gear;
    public int speed;
          
    // the Bicycle class has one constructor
    public Bicycle(int gear, int speed)
    {
        this.gear = gear;
        this.speed = speed;
    }
          
    // the Bicycle class has three methods
    public void applyBrake(int decrement)
    {
        speed -= decrement;
    }
          
    public void speedUp(int increment)
    {
        speed += increment;
    }
      
    // toString() method to print info of Bicycle
    public String toString() 
    {
        return("No of gears are "+gear
                +"\n"
                + "speed of bicycle is "+speed);
    } 
}
  
// derived class
class MountainBike extends Bicycle 
{
      
    // the MountainBike subclass adds one more field
    public int seatHeight;
  
    // the MountainBike subclass has one constructor
    public MountainBike(int gear,int speed,
                        int startHeight)
    {
        // invoking base-class(Bicycle) constructor
        super(gear, speed);
        seatHeight = startHeight;
    } 
          
    // the MountainBike subclass adds one more method
    public void setHeight(int newValue)
    {
        seatHeight = newValue;
    } 
      
    // overriding toString() method
    // of Bicycle to print more info
    @Override
    public String toString()
    {
        return (super.toString()+
                "\nseat height is "+seatHeight);
    }
      
}
  
// driver class
public class Test 
{
    public static void main(String args[]) 
    {
          
        MountainBike mb = new MountainBike(3, 100, 25);
        System.out.println(mb.toString());
              
    }
}
brightness_4
Output:
No of gears are 3
speed of bicycle is 100
seat height is 25
In above program, when an object of MountainBike class is created, a copy of the all
methods and fields of the superclass acquire memory in this object. That is why, by
using the object of the subclass we can also access the members of a superclass.
Please note that during inheritance only object of subclass is created, not the
superclass. For more, refer Java Object Creation of Inherited Class.
Illustrative image of the program: 

In practice, inheritance and polymorphism are used together in java to achieve fast


performance and readability of code.
Types of Inheritance in Java
Below are the different types of inheritance which is supported by Java.
1. Single Inheritance : In single inheritance, subclasses inherit
the features of one superclass. In image below, the class A serves
as a base class for the derived class B.

filter_none
edit
play_arrow
brightness_4
//Java program to illustrate the 
// concept of single inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
  
class one
{
    public void print_geek()
    {
        System.out.println("Geeks");
    }
}
  
class two extends one
{
    public void print_for()
    {
        System.out.println("for");
    }
}
// Driver class
public class Main
{
    public static void main(String[] args)
    {
        two g = new two();
        g.print_geek();
        g.print_for();
        g.print_geek();
    }
}
Output:
Geeks
for
Geeks

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 below image, the 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.

filter_none
edit
play_arrow
brightness_4
// Java program to illustrate the 
// concept of Multilevel inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
  
class one
{
    public void print_geek()
    {
        System.out.println("Geeks");
    }
}
  
class two extends one
{
    public void print_for()
    {
        System.out.println("for");
    }
}
  
class three extends two
{
    public void print_geek()
    {
        System.out.println("Geeks");
    }
}
  
// Drived class
public class Main
{
    public static void main(String[] args)
    {
        three g = new three();
        g.print_geek();
        g.print_for();
        g.print_geek();
    }
}
Output:
Geeks
for
Geeks

3. Hierarchical Inheritance : In Hierarchical Inheritance, one


class serves as a superclass (base class) for more than one sub
class.In below image, the class A serves as a base class for the
derived class B,C and D.
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate the 
// concept of Hierarchical inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
  
class one
{
    public void print_geek()
    {
        System.out.println("Geeks");
    }
}
  
class two extends one
{
    public void print_for()
    {
        System.out.println("for");
    }
}
  
class three extends one
{
    /*............*/
}
  
// Drived class
public class Main
{
    public static void main(String[] args)
    {
        three g = new three();
        g.print_geek();
        two t = new two();
        t.print_for();
        g.print_geek();
    }
}
Output:
Geeks
for
Geeks

4. Multiple Inheritance (Through Interfaces) : In Multiple


inheritance ,one class can have more than one superclass and
inherit features from all parent classes. Please note that Java
does notsupport multiple inheritance with classes. In java, we can
achieve multiple inheritance only through Interfaces. In image
below, Class C is derived from interface A and B.

filter_none
edit
play_arrow
brightness_4
// Java program to illustrate the 
// concept of Multiple inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
   
interface one
{
    public void print_geek();
}
   
interface two
{
    public void print_for();
}
   
interface three extends one,two
{
    public void print_geek();
}
class child implements three
{
    @Override
    public void print_geek() {
        System.out.println("Geeks");
    }
   
    public void print_for()
    {
        System.out.println("for");
    }
}
  
// Drived class
public class Main
{
    public static void main(String[] args)
    {
        child c = new child();
        c.print_geek();
        c.print_for();
        c.print_geek();
    }
}
Output:
Geeks
for

Geeks
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 inheritance with classes, the hybrid inheritance is
also not possible with classes. In java, we can achieve hybrid
inheritance only through Interfaces.
Important facts about inheritance in Java
 Default superclass: Except Object class, which has no superclass, every
class has one and only one direct superclass (single inheritance). In the
absence of any other explicit superclass, every class is implicitly a subclass
of Object class.
 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 inheritance with classes. Although with
interfaces, multiple inheritance is 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 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 can be defined as the process where one class acquires the
properties (methods and fields) of another. With the use of inheritance
the information is made manageable in a hierarchical order.

The class which inherits the properties of other is known as subclass


(derived class, child class) and the class whose properties are inherited is
known as superclass (base class, parent class).

extends Keyword
extends is the keyword used to inherit the properties of a class.
Following is the syntax of extends keyword.

Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}

Sample Code
Following is an example demonstrating Java inheritance. In this example,
you can observe two classes namely Calculation and My_Calculation.

Using extends keyword, the My_Calculation inherits the methods


addition() and Subtraction() of Calculation class.

Copy and paste the following program in a file with name


My_Calculation.java

Example
 Live Demo

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);

public class My_Calculation 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;

My_Calculation demo = new My_Calculation();

demo.addition(a, b);

demo.Subtraction(a, b);

demo.multiplication(a, b);

Compile and execute the above code as shown below.


javac My_Calculation.java
java My_Calculation

After executing the program, it will produce the following result −

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.

The Superclass reference variable can hold the subclass object, but using
that variable you can access only the members of the superclass, so to
access the members of both classes it is recommended to always create
reference variable to the subclass.

If you consider the above program, you can instantiate the class as given
below. But using the superclass reference variable ( cal in this case) you
cannot call the method multiplication(), which belongs to the subclass
My_Calculation.

Calculation demo = new My_Calculation();

demo.addition(a, b);

demo.Subtraction(a, b);

Note − 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.

The super keyword


The super keyword is similar to this keyword. Following are the
scenarios where the super keyword is used.

 It is used to differentiate the members of superclass from the members of


subclass, if they have same names.

 It is used to invoke the superclass constructor from subclass.

Differentiating the Members


If a class is inheriting the properties of another class. And if the members
of the superclass have the names same as the sub class, to differentiate
these variables we use super keyword as shown below.
super.variable
super.method();

Sample Code
This section provides you a program that demonstrates the usage of
the super keyword.

In the given program, you have two classes


namely Sub_class and Super_class, both have a method named display()
with different implementations, and a variable named num with different
values. We are invoking display() method of both classes and printing
the value of the variable num of both classes. Here you can observe that
we have used super keyword to differentiate the members of superclass
from subclass.

Copy and paste the program in a file with name Sub_class.java.

Example
 Live Demo

class Super_class {

int num = 20;

// display method of superclass

public void display() {

System.out.println("This is the display method of superclass");

public class Sub_class extends Super_class {

int num = 10;

// display method of sub class

public void display() {


System.out.println("This is the display method of subclass");

public void my_method() {

// Instantiating subclass

Sub_class sub = new Sub_class();

// Invoking the display() method of sub class

sub.display();

// Invoking the display() method of superclass

super.display();

// printing the value of variable num of subclass

System.out.println("value of the variable named num in sub class:"+


sub.num);

// printing the value of variable num of superclass

System.out.println("value of the variable named num in super class:"+


super.num);

public static void main(String args[]) {

Sub_class obj = new Sub_class();

obj.my_method();

Compile and execute the above code using the following syntax.
javac Super_Demo
java Super

On executing the program, you will get the following result −


Output
This is the display method of subclass
This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20

Invoking Superclass Constructor


If a class is inheriting the properties of another class, the subclass
automatically acquires the default constructor of the superclass. But if
you want to call a parameterized constructor of the superclass, you need
to use the super keyword as shown below.
super(values);

Sample Code
The program given in this section demonstrates how to use the super
keyword to invoke the parametrized constructor of the superclass. This
program contains a superclass and a subclass, where the superclass
contains a parameterized constructor which accepts a integer value, and
we used the super keyword to invoke the parameterized constructor of
the superclass.

Copy and paste the following program in a file with the name
Subclass.java

Example
 Live Demo

class Superclass {

int age;

Superclass(int age) {

this.age = age;

public void getAge() {

System.out.println("The value of the variable named age in super class is: "
+age);

}
}

public class Subclass extends Superclass {

Subclass(int age) {

super(age);

public static void main(String argd[]) {

Subclass s = new Subclass(24);

s.getAge();

Compile and execute the above code using the following syntax.
javac Subclass
java Subclass

On executing the program, you will get the following result −

Output
The value of the variable named age in super class is: 24

You might also like