
How can we use inheritance in java program?

class Animal {
public void eat(String str) {
System.out.println("Eating for grass");
}
}
class Cat extends Animal {
public void eat(String str) {
System.out.println("Drinking for milk");
}
}
class Dog extends Animal {
public void eat(String str) {
System.out.println("Eating for bread");
}
}
class Goat extends Animal {
public void eat(String str) {
System.out.println("");
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Animal();
Cat b = new Cat();
Dog c = new Dog();
Goat d = new Goat();
a.eat("grass");
b.eat("milk");
c.eat("bread");
d.eat("grass");
}
}
Output
Eating for grass Drinking for milk Eating for bread
Description:- The above example demonstrates you the concept of inheritance. Inheritance is a way of establishing a subtype from an existing object. In other words, it is the property of accessing properties, methods of super class by a sub class. With the use of extends keyword, the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass. In the given example, the class Animal is a superclass, whose method eat() has been accessed by its sub classes Cat, Dog and Goat. The objects of the subclasses is then created in the main class to test. Through the objectsof these class, their respective methods has been called.
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.