// 定义一个抽象类 Animal
abstract class Animal {
// 抽象方法,子类必须实现
public abstract void makeSound();
// 普通方法,子类可以直接继承或重写
public void eat() {
System.out.println("This animal is eating.");
}
}
// 继承抽象类 Animal 的具体类 Dog
class Dog extends Animal {
// 实现抽象方法 makeSound
public void makeSound() {
System.out.println("Dog says: Woof!");
}
}
// 继承抽象类 Animal 的具体类 Cat
class Cat extends Animal {
// 实现抽象方法 makeSound
public void makeSound() {
System.out.println("Cat says: Meow!");
}
}
// 测试类
public class TestAbstractClass {
public static void main(String[] args) {
// 创建 Dog 和 Cat 对象
Animal myDog = new Dog();
Animal myCat = new Cat();
// 调用 makeSound 方法
myDog.makeSound(); // 输出: Dog says: Woof!
myCat.makeSound(); // 输出: Cat says: Meow!
// 调用 eat 方法
myDog.eat(); // 输出: This animal is eating.
myCat.eat(); // 输出: This animal is eating.
}
}
Animal:定义了一个抽象方法 makeSound() 和一个普通方法 eat()。抽象方法没有具体的实现,必须由子类实现。Dog 和 Cat:继承了抽象类 Animal,并实现了抽象方法 makeSound()。TestAbstractClass:创建了 Dog 和 Cat 对象,并调用了它们的 makeSound() 和 eat() 方法。通过这种方式,抽象类提供了一种模板机制,允许子类根据需要实现特定的行为。
上一篇:java contains
下一篇:java transient
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站