Inheritance in java is one of the core concepts of Object-Oriented Programming. Java Inheritance is used when we have is-a relationship between objects. Inheritance in Java is implemented using extends keyword.
Inheritance in Java
Inheritance in Java is the method to create a hierarchy between classes by inheriting from other classes.
Java Inheritance is transitive - so if Sedan extends Car and Car extends Vehicle, then Sedan is also inherited from the Vehicle class. The Vehicle becomes the superclass of both Car and Sedan.
Inheritance is widely used in java applications, for example extending the Exception class to create an application-specific Exception class that contains more information such as error codes. For example NullPointerException.
Java Inheritance Example
Every class in java implicitly extends java.lang.Object class. So Object class is at the top level of inheritance hierarchy in java.
Let’s see how to implement inheritance in java with a simple example.
Superclass: Animal
package com.journaldev.inheritance; public class Animal { private boolean vegetarian; private String eats; private int noOfLegs; public Animal(){} public Animal(boolean veg, String food, int legs){ this.vegetarian = veg; this.eats = food; this.noOfLegs = legs; } public boolean isVegetarian() { return vegetarian; } public void setVegetarian(boolean vegetarian) { this.vegetarian = vegetarian; } public String getEats() { return eats; } public void setEats(String eats) { this.eats = eats; } public int getNoOfLegs() { return noOfLegs; } public void setNoOfLegs(int noOfLegs) { this.noOfLegs = noOfLegs; } }The Animal is the base class here. Let’s create a Cat class that inherits from Animal class.
Subclass: Cat
package com.journaldev.inheritance; public class Cat extends Animal{ private String color; public Cat(boolean veg, String food, int legs) { super(veg, food, legs); this.color="White"; } public Cat(boolean veg, String food, int legs, String color){ super(veg, food, legs); this.color=color; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } }Notice that we are using extends keyword to implement inheritance in java.
Java Inheritance Test Program
Let’s write a simple test class to create a Cat object and use some of its methods.
package com.journaldev.inheritance; public class AnimalInheritanceTest { public static void main(String[] args) { Cat cat = new Cat(false, "milk", 4, "black"); System.out.println("Cat is Vegetarian?" + cat.isVegetarian()); System.out.println("Cat eats " + cat.getEats()); System.out.println("Cat has " + cat.getNoOfLegs() + " legs."); System.out.println("Cat color is " + cat.getColor()); } }Output:
View YouTube video View YouTube video
You can checkout more inheritance examples from our GitHub Repository.
Reference: Oracle Documentation