Java Inheritance

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


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.