これは、継承について勉強中にオンラインで見つけた例です。Javaの継承とメソッドのオーバーライド
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal();
Animal b = new Dog();
a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class
}
}
私の主な混乱がメインメソッドの行です:私は理解してAnimal b = new Dog();
:
- 動物が
- bはメモリの新しいオブジェクト参照
- あるクラス名です割り当て
- 犬はコンストラクタコールです
しかし、 'b'はあまりにも正確に言及していますか? Animal b = new Dog();
とは何ですか? DogがAnimalを継承している場合、なぜAnimal b = new Dog
で、Dog b = new Dog();
ではないのですか?私はAnimal b = new Dog();
動物のB =新しい犬()、動物の参照と犬のオブジェクトを意味? –
'B'がDog' 'のインスタンスを参照しているが、 'B'は、羊の服で' Animal' ...オオカミのインスタンスとして動作している - 多型 – MadProgrammer
への歓迎をあなたは '一覧リスト=新しいのArrayListを<使用しない理由>() '?特定の実装からコードを分離する。動物や犬と同じです。あなたの犬が猫になったとき、動物を使用することはまだ正しいので、コードには1回の変更しか必要ありません。 –