用Java语言写一个定义超类,并通过继承定义子类,在子类中重写方法的例子
时间: 2024-03-13 21:42:48 浏览: 42
好的,下面是一个用Java语言编写的例子,包括定义超类`Animal`和继承自`Animal`的子类`Cat`和`Dog`,并在子类中重写`Animal`的`makeSound`方法。
```java
// 定义超类 Animal
public class Animal {
public void makeSound() {
System.out.println("This is an animal sound.");
}
}
// 定义子类 Cat,继承自 Animal
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("This is a cat sound: Meow!");
}
}
// 定义子类 Dog,继承自 Animal
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("This is a dog sound: Woof!");
}
}
// 测试代码
public class Test {
public static void main(String[] args) {
Animal animal = new Animal();
animal.makeSound();
Cat cat = new Cat();
cat.makeSound();
Dog dog = new Dog();
dog.makeSound();
}
}
```
输出结果为:
```
This is an animal sound.
This is a cat sound: Meow!
This is a dog sound: Woof!
```
在此例子中,`Cat`和`Dog`均继承自`Animal`,并且分别重写了`makeSound`方法,以便实现各自特有的声音。在测试代码中,分别创建了`Animal`、`Cat`和`Dog`对象,并调用它们的`makeSound`方法,输出各自的声音。
阅读全文