Below is a complete example of single inheritance in Java, including the code and the expected output.
Example Code
// Superclass
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Subclass
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
// Main class to test the inheritance
public class SingleInheritanceTest {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited method from Animal class
myDog.bark(); // Method from Dog class
}
}
Explanation
Superclass’
Animal
‘:- It has a method ‘
eat()
‘ that prints “This animal eats food.”.
- It has a method ‘
Subclass ‘
Dog
‘:- It inherits from ‘
Animal'
. - It has an additional method ‘
bark()
‘ that prints “The dog barks.”.
- It inherits from ‘
Main Class ‘
SingleInheritanceTest
‘:- It creates an instance of ‘
Dog
‘. - It calls the inherited ‘
eat()
‘ method and the ‘bark()
‘ method from the ‘Dog
‘ class.
- It creates an instance of ‘
Expected Output
This animal eats food.
The dog barks.
Detailed Explanation of Output
- When
myDog.eat()
is called, it executes theeat()
method defined in theAnimal
class, producing the output “This animal eats food.”. - When
myDog.bark()
is called, it executes thebark()
method defined in theDog
class, producing the output “The dog barks.”.
This simple example demonstrates how single inheritance allows the Dog
class to inherit behavior from the Animal
class and extend it with additional functionality.