给一段Java 继承 代码示例
时间: 2023-12-14 16:04:08 浏览: 35
以下是一个简单的Java代码示例,展示了继承的概念:
```java
// 父类 Animal
class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + "正在吃东西");
}
}
// 子类 Dog 继承自 Animal
class Dog extends Animal {
private String breed;
public Dog(String name, String breed) {
super(name);
this.breed = breed;
}
public void bark() {
System.out.println(name + "(品种:" + breed + ")正在汪汪叫");
}
}
// 子类 Cat 继承自 Animal
class Cat extends Animal {
private int age;
public Cat(String name, int age) {
super(name);
this.age = age;
}
public void meow() {
System.out.println(name + "(年龄:" + age + ")正在喵喵叫");
}
}
public class InheritanceExample {
public static void main(String[] args) {
Dog dog = new Dog("旺财", "哈士奇");
dog.eat(); // 调用父类的方法
dog.bark(); // 调用子类特有的方法
Cat cat = new Cat("咪咪", 3);
cat.eat(); // 调用父类的方法
cat.meow(); // 调用子类特有的方法
}
}
```
在上面的示例中,`Animal` 是父类,`Dog` 和 `Cat` 是子类。子类通过继承父类,获得了父类的属性和方法。子类可以在父类的基础上添加自己的特性和方法。在 `InheritanceExample` 类的 `main` 方法中,创建了一个 `Dog` 对象和一个 `Cat` 对象,并分别调用了它们的方法。
运行这段代码,输出结果如下:
```
旺财正在吃东西
旺财(品种:哈士奇)正在汪汪叫
咪咪正在吃东西
咪咪(年龄:3)正在喵喵叫
```
这个示例展示了继承的基本用法,子类通过继承父类获得了共同的功能,同时可以有自己特有的功能。