关于 Java 中覆盖的说明

Clarification about overriding in 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 reference and object
      Animal b = new Dog(); // Animal reference but Dog object

      a.move();// runs the method in Animal class

      b.move();//Runs the method in Dog class
   }
}

在调用 b.move() 时,方法 "move() under the Dog class" 已覆盖 "move() under the Animal class" 是否正确,因为 Dog 对象在调用相同方法时优先动物类型?

我注意到很多网站并没有对此进行解释,而是只是抛出一些例子,而不是逐行讨论这些内容。只是想消除我的术语混淆。

旁注,是否可以拥有 Dog 对象但调用 Animal class 下的 move()?例如有这样的东西:

Dog doggy = new Dog();
doggy.move()
>>>
Animals can move
>>>

这可能吗? ((Animal) doggy).move() 会完成这个吗?

使用super关键字调用父成员函数或数据成员。

喜欢:super.move(); 在这种情况下,您的父函数将被调用。

来自oracle docs

If two or more independently defined default methods conflict, or a default method conflicts with an abstract method, then the Java compiler produces a compiler error. You must explicitly override the supertype methods.

所以基本上,如果你在 sub-class 中调用一个在 superclass 中的方法,你将无法调用 super-class ]' 方法,除非您使用 super.function()Read up more on it here

你可以这样做

    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 void moveParent() {
       super.move();

   }

}

public class Main{

   public static void main(String args[]){
      Animal a = new Animal(); // Animal reference and object
      Animal b = new Dog(); // Animal reference but Dog object

      a.move();// runs the method in Animal class

      b.move();//Runs the method in Dog class

      Dog doggy = new Dog();
      doggy.moveParent();

   }
}

绝对正确,在调用 b.move() 时说 Dog class 下的方法“move()”覆盖了“move() 下的方法” Animal class".

对于第二个问题,你应该将 class Dog 实现为:

public class Dog extends Animal {

   public void move(){
     super.move();
   }
}

第三题,答案是"NO"。

          ((Animal) doggy).move()

这只是 'redundant' 并在 Dog class 下给出输出“move()”。

这是面向对象编程(又名 OOP)的原则 - 多态性。狗,猫,大象都是动物。

Animal d = new Dog();
Animal c = new Cat();
Animal t = new Tiger()

那一定不在乎,总是对的。 :)