// 定义一个父类 Animal
class Animal {
// 父类中的方法
public void eat() {
System.out.println("This animal eats food.");
}
}
// 定义一个子类 Dog,继承自 Animal
class Dog extends Animal {
// 子类中可以重写父类的方法
@Override
public void eat() {
System.out.println("The dog eats dog food.");
}
// 子类中还可以添加新的方法
public void bark() {
System.out.println("The dog barks.");
}
}
public class Main {
public static void main(String[] args) {
// 创建 Dog 类的实例
Dog myDog = new Dog();
// 调用从 Animal 继承来的方法
myDog.eat(); // 输出: The dog eats dog food.
// 调用 Dog 类自己的方法
myDog.bark(); // 输出: The dog barks.
}
}
eat
方法。extends
关键字继承了 Animal
类。它重写了 eat
方法,并且添加了一个新的方法 bark
。main
方法用于执行程序。在 main
方法中,创建了一个 Dog
类的实例,并调用了其继承和新增的方法。通过这种方式,extends
关键字允许子类继承父类的属性和方法,并可以根据需要进行扩展或重写。
上一篇:java获取项目根目录路径
下一篇:java 规则引擎
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站