java关于子类和继承

img

子类和继承:编写主类MyApp,在主类MyApp的main方法中至少包含如下代码:
Simulator simulator=new Simulator();
simulator. playSound (new Dog());
simulator.playSound (new Cat ());

望采纳

public class MyApp {
    public static void main(String[] args) {
        Simulator simulator = new Simulator();
        simulator.playSound(new Dog());
        simulator.playSound(new Cat());
    }
}

class Animal {
    public void makeSound() {
        System.out.println("Animal is making a sound.");
    }
}

class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Dog is barking.");
    }
}

class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Cat is meowing.");
    }
}

class Simulator {
    public void playSound(Animal animal) {
        animal.makeSound();
    }
}