继承在 Java 中实现为超类或接口的方法/字段的简单扩展,分别使用 extends 或 implements 关键字。无论哪种方式,您都可以在子类中访问超类的公共和受保护数据成员,而从外部对子类进行操作时,只能访问公共数据成员。
以你的例子为例,你可以定义几个类:
class Animal {
private int location;
public Animal() {
location = 0;
}
public void move() {
location += 10;
}
public int getLocation() {
return location;
}
}
class Dog extends Animal {
@Override
public void move() {
setLocation(getLocation() + 5);
}
}
/*
* The @Override flag is optional, but I prefer to put it there
* to ensure that I am actually overriding a method or implementing
* a method from an interface.
*/
class Cat extends Animal {
@Override
public void move() {
setLocation(getLocation() + 15);
}
}
所以Dog 和Cat 都扩展了Animal - 这是一种继承关系。
多态是完全不同的东西。根据维基百科:
多态性在工业中的主要用途(面向对象的编程理论)是属于不同类型的对象能够响应同名的方法、字段或属性调用,每个调用根据适当的特定类型行为。
用简单的英语术语来说,这只是意味着采取相同的想法或行动,并根据其具体类型的对象以不同的方式实现它。在代码中:
public static void main(String[] args) {
Animal animalArray = {
new Animal(),
new Cat(),
new Dog()
};
for (Animal a : animalArray) {
a.move();
}
System.out.println("Animal location: " + animalArray[0].getLocation());
System.out.println("Cat location: " + animalArray[1].getLocation());
System.out.println("Dog location: " + animalArray[2].getLocation));
}
这会产生输出:
Animal location: 10
Cat location: 15
Dog location: 5
请注意,每个对象,Animal、Cat 和 Dog 都作为 Animals 访问。这是可能的,因为每个类都是或扩展Animal,因此每个类都将始终拥有公共方法move(),在某些情况下它只是被重新定义。
接口的工作原理相同;如果一个类扩展了一个接口,则可以保证接口中定义的每个方法都有一些实现,因此可以根据接口实现的方法来使用它。