Inheritance in Java

In this section, you will learn about the inheritance with an example and its description Inheritance can be defined as the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order. When we talk about inheritance, the most commonly used keyword would be extends and implements. These words would determine whether one object IS-A type of another. By using these keywords we can make one object acquire the properties of another object.

Why use inheritance in java

  • For Method Overriding (so runtime polymorphism can be achieved).
  • For Code Reusability.

Syntax of Java Inheritance

 class Subclass-name extends Superclass-name 
{ 
//methods and fields
} 

Example of Code Reusablity

 class Person
{
String name="John";
int age=23;
}
class Student extends Person
{
String course="JAVA";
public static void main(Stringar[])
{
Students=new Student();
System.out.println("name is : "+s.name);
System.out.println("age is : "+s.age);
System.out.println("course is : "+s.course);
}
}
Output    :
name is   : John
age is    : 23
course is : JAVA

In the above example, Student object can access the field of own class as well as of Person class i.e. code reusability.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.

Second1
Note: Multiple inheritance is not supported in java through class

When a class extends multiple classes i.e. known as multiple inheritance. For Example:

Second1

Q) Why multiple inheritance is not supported in java?

Answer : To reduce the complexity and simplify the language, multiple inheritance is not supported in java. We can assume a scenario like, there are three classes named One, Two and Three. Class One extends the class Two and Three, and class Two and Three has method with the same name and same signature.

class Three
{
public void print()
{
    System.out.println("this is Three");
}
}
class Two
{
public void print()
{
    System.out.println("this is Two");
}
}

class One extends Two, Three //Suppose it would be
{
public static void main(String ar[])
{
    One o=new One();
    o.print();//here is ambiguity to invoke whose print method
}
}

Output

One.java:17: error: '{' expected
class One extends Two, Three //Suppose it would be
Compile time error

			   

Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.