// 定义一个父类 Animal
class Animal {
// 成员变量
String name;
// 构造方法
public Animal(String name) {
this.name = name;
}
// 成员方法
public void eat() {
System.out.println(name + " is eating.");
}
}
// 定义一个子类 Dog,继承自 Animal
class Dog extends Animal {
// 子类特有的成员变量
String breed;
// 构造方法
public Dog(String name, String breed) {
// 调用父类的构造方法
super(name);
this.breed = breed;
}
// 重写父类的方法
@Override
public void eat() {
System.out.println(name + " the " + breed + " is eating dog food.");
}
// 子类特有的方法
public void bark() {
System.out.println(name + " the " + breed + " is barking.");
}
}
// 测试类
public class InheritanceExample {
public static void main(String[] args) {
// 创建父类对象
Animal animal = new Animal("Generic Animal");
animal.eat();
// 创建子类对象
Dog dog = new Dog("Buddy", "Golden Retriever");
dog.eat();
dog.bark();
}
}
父类 Animal:
name 和一个构造方法。eat(),用于表示动物进食的行为。子类 Dog:
Animal 类。breed 表示狗的品种。eat() 方法,以提供更具体的行为。bark(),这是 Dog 类特有的行为。测试类 InheritanceExample:
Animal 对象和一个 Dog 对象,并调用了它们的方法。上一篇:java的继承
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站