// 父类
class Animal {
public void makeSound() {
System.out.println("动物发出声音");
}
}
// 子类1
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("狗发出汪汪声");
}
public void makeSound(String barkType) {
System.out.println("狗发出" + barkType + "声");
}
}
// 子类2
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("猫发出喵喵声");
}
public void makeSound(int meowLevel) {
for (int i = 0; i < meowLevel; i++) {
System.out.print("喵");
}
System.out.println();
}
}
// 测试类
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog(); // 创建Dog对象
Animal myCat = new Cat(); // 创建Cat对象
myDog.makeSound(); // 调用Dog的makeSound方法
((Dog) myDog).makeSound("大声"); // 调用Dog的重载makeSound方法
myCat.makeSound(); // 调用Cat的makeSound方法
((Cat) myCat).makeSound(3); // 调用Cat的重载makeSound方法
}
}
07-21
1523
12-17
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交