Advertisement

Google Ad Slot: content-top

Java Inheritance

~1 min read · Java
On this page

Inheritance is one of the key principles of Object-Oriented Programming (OOP). It allows a class (child or subclass) to inherit the properties (fields) and behaviors (methods) of another class (parent or superclass). This helps in code reuse and establishing a hierarchical relationship between classes.


Syntax:

class Parent {
    // Parent class properties and methods
}

class Child extends Parent {
    // Child class properties and methods
}

Types of Inheritance

Java supports the following types of inheritance:

1.Single Inheritance: A class inherits from one parent class.

Example
class Animal { void eat() { System.out.println("This animal can eat."); } } class Dog extends Animal { void bark() { System.out.println("The dog barks."); } } public class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.eat(); // Inherited from Animal dog.bark(); // Defined in Dog } }
Try it yourself

2.Multilevel Inheritance: A class inherits from another class, which itself is a subclass of another class.

Example
class Animal { void eat() { System.out.println("This animal can eat."); } } class Mammal extends Animal { void walk() { System.out.println("Mammals can walk."); } } class Dog extends Mammal { void bark() { System.out.println("The dog barks."); } } public class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.eat(); // Inherited from Animal dog.walk(); // Inherited from Mammal dog.bark(); // Defined in Dog } }
Try it yourself

3.Hierarchical Inheritance: Multiple classes inherit from the same parent class.

Example
class Animal { void eat() { System.out.println("This animal can eat."); } } class Dog extends Animal { void bark() { System.out.println("The dog barks."); } } class Cat extends Animal { void meow() { System.out.println("The cat meows."); } } public class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.eat(); dog.bark(); Cat cat = new Cat(); cat.eat(); cat.meow(); } }
Try it yourself