In this article, we will learn about Inheritance in Java, through detailed examples.
Table of Contents
1. Why we need Java Inheritance?
Inheritance in Java is the ability of a class to inherit fields and methods from another class. So we can say that a class extends to another class. When we use the ability of Inheritance the two classes have certain roles. The class that inherits from another class is called a subclass and the class that is inherited is called a superclass. In other words, the subclass inherits fields and methods from the superclass.
2. extends Keyword
In order for the subclass to inherit from the superclass, we need to use the extends
keyword. Let’s see the syntax of extends
keyword.
class SuperClass { ..... } class SubClass extends SuperClass { ..... }
Now let’s see a simple example:
public class Animal { public String question = "What is that?"; public void noise() { System.out.println("I can't here clearly but I think it's an Animal. "); } }
public class Dog extends Animal{ public String secondAnswer = "It's definitely a dog!!"; public static void main(String[] args){ Dog ob=new Dog(); System.out.println(ob.question); ob.noise(); System.out.println(ob.secondAnswer); } }
In this example, we can see that the Dog
class inherits the method and the question
variable from the Animal
class and with the help of an object has the ability to call the method and print the variable. The output is:
What is that? I can't hear clearly but i think it's an Animal. It's definitely a dog!!
3. super Keyword
We use the super keyword in Java to refer immediate parent class object. So whenever you want to create an instance of a subclass, Java implicitly creates an instance of the parent class which Java refers to as the super reference variable.
There are 3 ways to use the super keyword. These are :
- It can be used to refer immediate parent class instance variable.
- Also, it can be used to invoke the immediate parent class method.
- Lastly, it can be used to invoke the immediate parent class constructor.
Let’s see some examples for these three usages:
3.1 Super Keyword for instance variables
In this example, we can see that with the super keyword we can access the data member or field of the parent class.
public class Animal { String animal="Animal"; } public class Dog extends Animal { String animal="Dog"; public void theAnimals(){ System.out.println(animal); System.out.println(super.animal); } } public class Test { public static void main(String[] args){ Dog dog = new Dog(); dog.theAnimals(); } }
The output is:
Dog Animal
3.2 Super Keyword to invoke immediate parent class method
Of course, we can use the super
keyword to invoke the parent class methods. It should be used if the subclass contains the same method as the parent class.
public class Animal { public void walk(){ System.out.println("Animal walking..."); } } public class Dog extends Animal { public void walk(){ System.out.println("Dog walking..."); } public void printMethods(){ super.walk(); walk(); } } public class Test { public static void main(String[] args) { Dog dog = new Dog(); dog.printMethods(); } }
The output is:
Animal walking... Dog walking...
3.3 Super Keyword to invoke immediate parent class constructor
Finally, we can use the super
keyword to invoke the parent class constructor. Note that the keyword super
must be in the first line of the constructor, otherwise, the code will not compile.
public class Animal { Animal(){ System.out.println("This is an Animal."); } } public class Dog extends Animal{ Dog() { super(); System.out.println("This is a Dog."); } } public class Test { public static void main(String[] args) { Dog dog = new Dog(); } }
The output is:
This is an Animal. This is a Dog.
4. Types of Relationships
Type of relationship gives us the ability to understand how to reuse a feature(method or field) from one class to another class. In Java programming, we have three types of relationships which are:
- IS-A Relationship: In Is-A relationship or Inheritance relationship, one class is obtaining the features of another class by using inheritance concept with extends keywords.
- HAS-A Relationship: In Has-A relationship or Association relationship, an object of one class is created as data member in another class.
- Uses-A Relationship: In Uses-A relationship or Dependence relationship, a method of one class is using an object of another class.
5. instanceof Keyword
The instanceof
keyword checks whether an object is an instance of a specific class or an interface. This keyword Java is also known as type comparison operator because it has the ability to compare the instance with type. The output can be true or false. Finally, if we apply the instanceof
operator with a null value, it returns false.
Let’s see an example:
public class InstanceOfExample { public static void main(String[] args){ InstanceOfExample ex1=new InstanceOfExample(); System.out.println(ex1 instanceof InstanceOfExample); InstanceOfExample ex2= null; System.out.println(ex2 instanceof InstanceOfExample); } }
In our first example, we check if ex1
object is an instance of the InstanceOfExample
class. In our second example, we check the instanceof
operator with a variable that has a null value. The output is:
true false
6. Types of Inheritance Java
In Java, there are 5 types of inheritance. The two of them are supported through the interface only. The types of Inheritance are:
- Single Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Multiple Inheritance (through interfaces only)
- Hybrid Inheritance
So let’s analyze these 5 types:
6.1 Single Inheritance
Creating subclasses from a single class is called single inheritance. In Inheritance, we can access superclass methods and variables and we can access subclass methods and variables through subclass objects.
Let’s see an example:
public class Animal { public void walk(){ System.out.println("walking.."); } } public class Dog extends Animal { public void sleep(){ System.out.println("sleeping.."); } } public class Test { public static void main(String[] args) { Dog dog = new Dog(); dog.walk(); dog.sleep(); } }
The output is:
walking.. sleeping..
6.2 Multilevel Inheritance
A class that extends to a class that is already extended from another class is called Multilevel Inheritance in Java. In other words, classes create a chain. For example, if there is a class A that extends class B and class B extends from another class C, then they follow a Multi-level Inheritance.
Let’s see an example:
public class Animal { public void walk(){ System.out.println("walking.."); } } public class Dog extends Animal{ public void sleep() { System.out.println("sleeping.."); } } public class Puppy extends Dog{ public void cry(){ System.out.println("crying.."); } } public class Test { public static void main(String[] args) { Puppy puppy = new Puppy(); Dog secondPuppy = new Puppy(); puppy.walk(); puppy.sleep(); puppy.cry(); secondPuppy.sleep(); secondPuppy.walk(); } }
In this example, we cannot call the cry()
method when using the object secondPuppy
since its type dictates which method can be called. As a result, the methods that can be called are that of Dog
and methods of parent classes(Animal
in this example is the only parent class).
The output is:
walking.. sleeping.. crying.. sleeping.. walking..
6.3 Hierarchical Inheritance
With Hierarchical Inheritance in Java, we can create more than one child classes that extend a single parent class, or in other words, a single parent class can have more than one child class.
Let’s see an example:
public class Animal { public void sleep(){ System.out.println("sleeping..."); } } public class Bird extends Animal { public void sing(){ System.out.println("singing..."); } } public class Dog extends Animal{ public void bark(){ System.out.println("barking..."); } } public class Test { public static void main(String[] args){ Bird bird = new Bird(); Dog dog = new Dog(); bird.sing(); bird.sleep(); dog.bark(); dog.sleep(); } }
The output is:
singing... sleeping... barking... sleeping...
6.4 Multiple Inheritance
If you want a class to extend multiple classes it is impossible in Java and the only way to achieve multiple inheritance is through interfaces.
Let’s see an example without Interfaces:
public class Animal { public void sleep(){ System.out.println("An animal is sleeping."); } } public class Dog { public void sleep(){ System.out.println("A dog is sleeping."); } } public class Puppy extends Animal, Dog { }
As we can see we can’t continue the example because we have a compilation error that says that: Class cannot extend multiple classes.
So in this case we need to use interfaces in order to create multiple Inheritance.
Note that we need to use Java 1.8 version or higher in order to use default methods inside the interfaces.
So without further ado, let’s see how the above example could be replicated with interfaces:
public interface Cat { default void sleep(){ System.out.println("A cat is sleeping."); } } public interface Dog { default void sleep(){ System.out.println("A dog is sleeping."); } } public class Test implements Cat, Dog { public void sleep() { Dog.super.sleep(); Cat.super.sleep(); } public static void main(String[] args){ Test test=new Test(); test.sleep(); } }
The output is:
A dog is sleeping. A cat is sleeping.
6.5 Hybrid Inheritance
Hybrid Inheritance in Java is a combination of different types of inheritance. In this type of Inheritance, more than one kind of inheritance is observed. If we have class A and class B that extend class C and then there is another class D that extends class A, then this is a Hybrid type of Inheritance.
In this example, you would be able to see how we have implemented two types of inheritance(single and hierarchical) together to form hybrid inheritance.
Class Dog and Cat extends class Animal → Hierarchical inheritance
Class Pat extends class Dog → Single inheritance
Let’s see an example:
public class Animal { public void sleep() { System.out.println("An animal is sleeping."); } } public class Cat extends Animal{ public void sleep() { System.out.println("An cat is sleeping."); } } public class Dog extends Animal{ public void sleep() { System.out.println("An dog is sleeping."); } } public class Pet extends Dog{ public void sleep() { System.out.println("A pet is sleeping."); } public static void main(String[] args){ Pet pet=new Pet(); pet.sleep(); } }
The output is:
A pet is sleeping.
7. Conclusion
By now, you should be able to create an Inheritance in Java and use it effectively. You can find the source code on our GitHub page.
8. Sources
[1]: Inheritance, Oracle