Java 抽象类测试示例:猫和狗的叫声
抽象思想指的是将共性提取出来,形成一个抽象的类或接口,用于定义规范和约束子类的行为。在这个例子中,可以定义一个抽象的 Animal 类,用于约束猫和狗的行为。
Animal 类:
public abstract class Animal {
public abstract void sound();
}
Cat 类:
public class Cat extends Animal {
public void sound() {
System.out.println('喵喵喵');
}
}
Dog 类:
public class Dog extends Animal {
public void sound() {
System.out.println('汪汪汪');
}
}
测试类:
public class Test {
public static void main(String[] args) {
Animal cat = new Cat();
Animal dog = new Dog();
cat.sound(); // 输出:喵喵喵
dog.sound(); // 输出:汪汪汪
}
}
在测试类中,我们使用 Animal 类型来声明猫和狗的对象,这样就能够调用 Animal 类中定义的方法 sound(),而具体的实现则由子类 Cat 和 Dog 来完成。这样做的好处是可以更好地实现代码的封装和扩展,同时也符合面向对象的设计原则。
原文地址: https://www.cveoy.top/t/topic/nQLD 著作权归作者所有。请勿转载和采集!