Code

// Parent classclass 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 Animalclass 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");    }}// UsageAnimal animal = new Dog("Buddy");animal.eat();    // Calls overridden methodanimal.sleep();  // Calls inherited method// animal.bark(); // Compile error - Animal doesn't have bark()Dog dog = new Dog("Buddy");dog.eat();   // Calls overridden methoddog.sleep(); // Calls inherited methoddog.bark();  // Calls Dog-specific method

Comments

No comments yet. Be the first!