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
Illustrate how Java supports multiple inheritance.
Create a class called Animal with a method sound() that displays a generic sound. Then, create a subclass called Dog that inherits from Animal and overrides the sound() method to display "Woof". Create another subclass called Cat that inherits from Animal and overrides the sound() method to display "Meow". Finally, create a subclass called Cow that inherits from Animal and overrides the sound() method to display "Moo". In the main method, create objects of Dog, Cat, and Cow classes and call the sound() method for each object
What is inheritance in Java?OptionsThe ability to create new classes from existing classesThe ability to create multiple instances of a classThe ability of a class to inherit fields and methods from its subclassThe ability of a subclass to inherit the fields and methods of its superclass
How does Java achieve a limited form of multiple inheritance?
What is the expected output?class Animal { Animal() { System.out.println("Animal"); }}class Wild extends Animal{ Wild() { System.out.println("Wild"); super(); }}public class Test { public static void main(String args[]) { Wild wild = new Wild(); }}
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.