Develop a Java program that demonstrates inheritance between two classes:the superclass Animal and its subclass Dog.
Question
Develop a Java program that demonstrates inheritance between two classes:
The superclass Animal and its subclass Dog.
Solution
Sure, here is a simple example of a Java program that demonstrates inheritance between two classes: the superclass Animal and its subclass Dog.
// This is the superclass Animal
public class Animal {
String name;
int age;
public void eat() {
System.out.println(name + " is eating");
}
public void sleep() {
System.out.println(name + " is sleeping");
}
}
// This is the subclass Dog
public class Dog extends Animal {
String breed;
public void bark() {
System.out.println(name + " is barking");
}
}
// This is the main class
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.name = "Rex";
myDog.age = 5;
myDog.breed = "Labrador";
myDog.eat();
myDog.sleep();
myDog.bark();
}
}
In this program, the Dog class is a subclass of the Animal class. This means that Dog inherits all the fields and methods of Animal. The Dog class can also define additional fields and methods, such as breed and bark(), that are not present in Animal.
In the Main class, we create an instance of Dog and call its methods. Since Dog is a subclass of Animal, it can use the eat() and sleep() methods defined in Animal, as well as the bark() method defined in Dog.
Similar Questions
What is the purpose of inheritance in Java? a.To allow code reuse and method overriding b.To import packages c.To declare variablesd.To secure data
Interfaces in Java can be used to achieve:Question 4Answera.Multiple inheritance.b.Code encapsulation.c.Method overloading.d.Static method implementation.
Which concept of Java is a way of converting real world objects in terms of class?Polymorphism1Inheritance2Abstraction3Encapsulatio
Which java keyword is used to inherit a class in Java?Question 18Answera.extendsb.derivesc.inheritsd.implements
In Java programming an object can take many forms. This feature called ______.OptionsPolymorphismAbstractionEncapsulationInheritance
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.