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 } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter