// Parent class
class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + " is eating");
}
public void sleep() {
System.out.println(name + " is sleeping");
}
}
// Child class inheriting from Animal
class Dog extends Animal {
public Dog(String name) {
super(name); // Call parent constructor
}
// Override parent method
@Override
public void eat() {
System.out.println(name + " is eating dog food");
}
// New method specific to Dog
public void bark() {
System.out.println(name + " is barking");
}
}
// Usage
Animal animal = new Dog("Buddy");
animal.eat(); // Calls overridden method
animal.sleep(); // Calls inherited method
// animal.bark(); // Compile error - Animal doesn't have bark()
Dog dog = new Dog("Buddy");
dog.eat(); // Calls overridden method
dog.sleep(); // Calls inherited method
dog.bark(); // Calls Dog-specific method