Write A Program In Java To Demonstrate Single Inheritance

0

Write A Program In Java To Demonstrate Single Inheritance.

Write A Program In Java To Demonstrate Single Inheritance

Before understanding the program we need to know about the single inheritance


Single inheritance is a concept in object-oriented programming where a class can inherit the properties and methods of another class. This allows you to create a new class based on an existing class, reusing its code and adding new functionality.


In single inheritance, a class can have only one superclass from which it inherits. This means that the subclass inherits all of the properties and methods of its superclass, but it can also add its own properties and methods.


Single inheritance allows you to create a hierarchy of classes where each class builds upon the functionality of its superclass. This can make your code more organized and easier to maintain because you can reuse code from existing classes instead of writing everything from scratch.


Here's a program in java that demonstrate the use of single inheritance


Program

class Animal {
    public void eat() {
        System.out.println("The animal is eating");
    }
}

class Dog extends Animal {
    public void bark() {
        System.out.println("The dog is barking");
    }
}

public class SingleInheritanceDemo {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat(); // calling method of parent class
        dog.bark(); // calling method of child class
    }
}

Output
The animal is eating The dog is barking

Explanation

In this program, we define a parent class animal with a method eat(). We then define a child class dog that extends the animal class and adds a method bark().


In the main() method, we create an instance of dog and call both eat() and bark() methods. Since the dog class extends the animal class, it inherits the eat() method from the animal class. The bark() method is specific to the dog class and is not present in the animal class.


As we can see, the dog class inherits the eat() method from the animal class, and we can call both the methods using an instance of dog.


❤️ I Hope This Helps You Understand, Click Here To Do More Exercise In Java Programming.

Tags

Post a Comment

0Comments
Post a Comment (0)