Method overriding

PHOTO EMBED

Mon Jul 08 2024 17:40:56 GMT+0000 (Coordinated Universal Time)

Saved by @projectrock

class Animal {

    // Method in the superclass

    void sound() {

        System.out.println("Animal makes a sound");

    }

}

class Dog extends Animal {

    // Overriding the sound method in the subclass

    @Override

    void sound() {

        System.out.println("Dog barks");

    }

}

class Cat extends Animal {

    // Overriding the sound method in the subclass

    @Override

    void sound() {

        System.out.println("Cat meows");

    }

}

public class Main {

    public static void main(String[] args) {

        Animal myDog = new Dog();

        Animal myCat = new Cat();

        myDog.sound(); // Outputs: Dog barks

        myCat.sound(); // Outputs: Cat meows

    }

}

content_copyCOPY