Home Article Practice 多彩的音乐

多彩的音乐

2024-05-19 17:57  views:495  source:与之二三事    

在这个案例中,Person 是一个抽象类,它定义了一个抽象方法 feedDog,这个方法在子类中被实现.
Dog 类有一个 getFood 方法,它接受一个 Person 类型的参数.根据传入的 Person 对象的类型,
Dog 类会调用不同的方法来模拟狗的反应.在 DogReactionSimulation 类的 main 方法中,
创建了一个 Dog 对象和三种类型的 Person,然后模拟了每种人喂狗的场景,并观察狗的反应.
abstract class Person {
abstract void feedDog(Dog dog);
}
class Owner extends Person {
@Override
void feedDog(Dog dog) {
dog.getFood(this);
}
}
class FamilyMember extends Person {
@Override
void feedDog(Dog dog) {
dog.getFood(this);
}
}
class Stranger extends Person {
@Override
void feedDog(Dog dog) {
dog.getFood(this);
}
}
class Dog {
void getFood(Person person) {
if (person instanceof Owner) {
happyJump();
} else if (person instanceof FamilyMember) {
eatNormally();
} else if (person instanceof Stranger) {
beCautiousAndBark();
}
}
private void happyJump(){
System.out.println("狗非常开心,欢快地跳跃.");
}
private void eatNormally(){
System.out.println("狗很平静地吃东西.");
}
private void beCautiousAndBark(){
System.out.println("狗很警惕,并发出叫声.");
}
}
public class DogReactionSimulation {
public static void main(String[] args) {
Dog dog = new Dog();
Owner owner = new Owner();
FamilyMember familyMember = new FamilyMember();
Stranger stranger = new Stranger();
System.out.println("主人喂狗:");
owner.feedDog(dog);
System.out.println("\n家人喂狗:");
familyMember.feedDog(dog);
System.out.println("\n陌生人喂狗:");
stranger.feedDog(dog);
}
}



Disclaimer: The above articles are added by users themselves and are only for typing and communication purposes. They do not represent the views of this website, and this website does not assume any legal responsibility. This statement is hereby made! If there is any infringement of your rights, please contact us promptly to delete it.

字符:    改为:
去打字就可以设置个性皮肤啦!(O ^ ~ ^ O)