// 定义一个抽象类 Animal
abstract class Animal {
// 抽象方法,子类必须实现
public abstract void makeSound();
// 普通方法,子类可以直接继承使用
public void eat() {
System.out.println("This animal is eating.");
}
}
// 定义一个具体类 Dog,继承自 Animal
class Dog extends Animal {
// 实现抽象方法 makeSound
public void makeSound() {
System.out.println("Dog says: Woof!");
}
}
// 定义一个具体类 Cat,继承自 Animal
class Cat extends Animal {
// 实现抽象方法 makeSound
public void makeSound() {
System.out.println("Cat says: Meow!");
}
}
// 测试类
public class Main {
public static void main(String[] args) {
// 创建 Dog 和 Cat 对象
Animal dog = new Dog();
Animal cat = new Cat();
// 调用 makeSound 方法
dog.makeSound(); // 输出: Dog says: Woof!
cat.makeSound(); // 输出: Cat says: Meow!
// 调用 eat 方法
dog.eat(); // 输出: This animal is eating.
cat.eat(); // 输出: This animal is eating.
}
}
Animal 是一个抽象类,它包含一个抽象方法 makeSound() 和一个普通方法 eat()。makeSound() 是一个抽象方法,没有具体实现,子类必须提供具体的实现。eat() 是一个普通方法,有具体实现,子类可以直接继承使用。Dog 和 Cat 是两个具体类,它们继承自 Animal 并实现了抽象方法 makeSound()。Main 类中创建了 Dog 和 Cat 的对象,并调用了它们的方法。通过这种方式,抽象类可以定义通用的行为和属性,而具体类则提供具体的实现。
上一篇:java 异步
下一篇:java service
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站