extends
継承は、またはimplements
キーワードをそれぞれ使用して、スーパークラスまたはインターフェースのメソッド/フィールドの単純な拡張としてJavaに実装されます。いずれの場合も、サブクラス内でスーパークラスのパブリックおよび保護されたデータメンバーにアクセスでき、外部からサブクラスを操作する場合は、パブリックデータメンバーのみにアクセスできます。
あなたの例をとると、いくつかのクラスの定義を持つことができます:
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
両方とも動物を拡張します-これは継承関係です。
ポリモーフィズムはまったく異なるものです。ウィキペディアによると:
業界でのポリモーフィズムの主な用途(オブジェクト指向プログラミング理論)は、異なるタイプに属するオブジェクトが、それぞれが適切なタイプ固有の動作に従って、同じ名前のメソッド、フィールド、またはプロパティの呼び出しに応答する機能です。
簡単な英語の用語では、これは単に同じアイデアまたはアクションを取り、それが特定のタイプのオブジェクトに基づいて異なる方法で実装することを意味します。コード内:
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
各オブジェクト、、、、およびはすべてsとしてアクセスされることに注意Animal
しCat
てDog
くださいAnimal
。これが可能なのは、すべてのクラスがであるか拡張されているためです。Animal
したがって、各クラスには常にパブリックメソッドがmove()
あり、場合によっては単純に再定義されます。
インターフェイスは同じ哲学で機能します。クラスがインターフェースを拡張する場合、インターフェースで定義されたすべてのメソッドの実装が保証されるため、インターフェースが実装するメソッドの観点から使用できます。