Inheritance JAVA (extends other class)

Inheritance is one of the key features of OOP that allows us to create a new class from an existing class.

The new class that is created is known as subclass (child or derived class) and the existing class from where the child class is derived is known as superclass (parent or base class).

The extends keyword is used to perform inheritance in Java. For example,

class Animal {

  // field and method of the parent class
  String name;
  public void eat() {
    System.out.println("I can eat");
  }
}

// inherit from Animal
class Dog extends Animal {

  // new method in subclass
  public void display() {
    System.out.println("My name is " + name);
  }
}

class Main {
  public static void main(String[] args) {

    // create an object of the subclass
    Dog labrador = new Dog();

    // access field of superclass
    labrador.name = "Rohu";
    labrador.display();

    // call method of superclass
    // using object of subclass
    labrador.eat();

  }
}
/*Output
My name is Rohu
I can eat
*/

In the above example, the Dog class is created by inheriting the methods and fields from the Animal class.

Here, Dog is the subclass and Animal is the superclass.

labrador.name = "Rohu";

labrador.eat();

Here, labrador is an object of Dog. However, name and eat() are the members of the Animal class.

Since Dog inherits the field and method from Animal, we are able to access the field and method using the object of the Dog.

In the above example, we have derived a subclass Dog from superclass Animal. Notice the statements,

Inheritance in Java is a mechanism in which one object acquires/inherit all the properties and behaviors of a parent object.

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes (Parent Class) like the following:

class Vehicle {

  protected String brand = "Ford";        // Vehicle attribute

  public void honk() {                    // Vehicle method

    System.out.println("Tuut, tuut!");

  }

}

//Here "Vehicle" is the superclass/prarent class and the "Car" is the subclass/child class
 
class Car extends Vehicle {

  private String modelName = "Mustang";    // Car attribute

  public static void main(String[] args) {

    // Create a myCar object
    Car myCar = new Car();

    // Call the honk() method (from the Vehicle class) on the myCar object
    myCar.honk();

    // Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
    System.out.println(myCar.brand + " " + myCar.modelName);

  }

}

When you inherit from an existing class, you can reuse methods and fields (class variables/attributes) of the parent class. Moreover, you can add new methods and fields in your current class (subclass/child calss) also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Reusability of code: It is one of the important features of inheritance. It is a good way to reuse the already existing code rather than creating the same code again and again. This feature not only saves time and money as we are reusing the properties, but it also increases reliability of code.

Method Overriding (runtime polymorphism): With the help of inheritance, it is possible to override the methods of base class so that base class method is easily used in derived class.

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. The meaning of “extends” is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.

Whenever a parent class and a child class both are having same data members then this concept is known as data hiding.

Whenever a parent class and a child class both are having ditto same functions then this concept is known as method overriding.

Whenever a parent class and a child class both are having same static functions then this concept is known as function hiding.

We cannot print super, there is a syntax error. Always data members of parent class is inherited by super

If you make any non static function of a class as final then it cannot be overridden by the child class that means to stop method overriding makes a function final.

 In Inheritance by default all data members and member functions of a parent class are available to child class if they are not private

 Inheritance defines is-a relationship between a super class(parent) and its sub class(child). 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 VehicleOrange can inherit from Fruit, and so on.

 extends keyword is used to show inheritance in java.

For example :

Suppose a class name Base.java

class Base
{
//Code of Base class
}

Another class Child.java use Inheritance to extends properties from Base class.

Class Child extends Base

{
//extends the properties of base class
}

In the above example, Child class will inherit field and methods of Base class.

There are 3 types of inheritance:

  1. Single Inheritance
  2. Multilevel Inheritance
  3. Hierarchical Inheritance
  4. Multiple Inheritance
  5. Hybrid Inheritance

1. Single Inheritance:

In Single inheritance one class is derived from one parent class. The below diagram shows single inheritance where Class B inherits from Class A.

2. Multilevel Inheritance:

In multilevel inheritance there is a concept of grand parent class as shown in below diagram class C inherits class B and class B inherits class A.

3. Hierarchical Inheritance:

In Hierarchical inheritance more than one sub classes is derived from a single parent class as shown in below diagram class B and C both are derived from single parent class A.

Important Note: Java does not support multiple Inheritance .

Why multiple inheritance is not supported in java:

Consider the above diagram which shows multiple inheritance. In this class D extends both class B & C. Here class B & C inherit the same method of class A.

Now the problem comes when class D is extending both class B & C and if class D wants to use same method then which method would be called?

That’s why multiple inheritance is not supported in java as to remove ambiguity.


Below is the program to show you the use of inheritance in java. For coding this we have used eclipse IDE.

Example 1 

Let’s inherit some fields and methods in Child class from Base class.

Base class is having 2 fields and 1 method:

Base.java

class Base
{
	int x=50;
	int y = 60;

//Addition method return integer value of x+y
	public int addition(){
		return x+y; //return 110

	}
}

Child class inherit addition method and x field from Base class:

Child.java

public class Child extends Base
{

	int z;
	public void subtraction(){
		
		//addition method and x filed is inherited from Base Class
		z = addition() - x;
		System.out.println(z);
	}

}

In the Main class we create Child object and calls subtraction method on it.

MainClass.java

public class MainClass {

public static void main(String[] args) {

Child child = new Child(); //Child object
child.subtraction();//Subtraction method called on child object

}

}

/* Output
60
*/

Example 2

Base.java:

class Base
{
int x=50;
}

Child.java:

public class Child extends Base
{
 int x=20;
 void show()
 {
  System.out.println(x);
 }
}

MainClass.java

public class MainClass {

	public static void main(String[] args) {
		
		Child c = new Child();
		c.show();

	}

}

/*

Output
20

*/

In the above Example2: program, prints the value of x = 20 because priority always goes to local variables.

So, in show() method of child class, we can access the member of parent class i.e. base class using super keyword.

It means if we want to print value of x = 50 also from the same above program then by using super keyword.

Example 3 of Inheritance using super keyword:

Base.java:

class Base

{

int x=50;

}

Child.java:

class Child extends Base
{

int x=20;

void show()
{

System.out.println(x);


System.out.println(super.x);
/* we can access member of parent class i.e base class using super keyword. Here super.x indicate the field of Base class*/

}

}

MainClass.Java

public class MainClass{

public static void main(String[] args)
{
Child c=new Child();
c.show();
}
}

/*

Output
20
50

*/


If you don’t want other classes to inherit from a class, use the final keyword:

If you try to access a final class, Java will generate an error:

final class Vehicle {
  ...
}

class Car extends Vehicle {
  ...
}

/*

Output

Main.java:9: error: cannot inherit from final Vehicle
class Main extends Vehicle {
                  ^
1 error)

*/

Inheritance allows the class to use the states and behavior of another class using extends keyword

Inheritance is-a relationship between a Base class and its child class.

Multiple inheritance is not supported in JAVA.