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