繁体   English   中英

关于覆盖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()时,是否正确地说,在Dog类下面的方法“move()”已经覆盖了Animal类下的“move()”,因为Dog对象在被引用时调用相同的方法时优先。动物类型?

我注意到很多网站都没有解释这个问题,而是他们只是抛出一些例子,而不是逐行讨论。 只是想澄清我的术语混乱。

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

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

这可能吗? 会((动物)小狗).move()完成这个?

当然,在调用b.move() ,在Dog类下面的方法“ move() ”覆盖了Animal类下的“ move() ”是正确的。

对于第二个问题,您应该将类​​Dog实现为:

public class Dog extends Animal {

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

对于第三个问题,答案是“不”。

          ((Animal) doggy).move()

这只是“冗余”,并在Dog类下输出“ move() ”。

你可以这样做

    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();

   }
}

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

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

来自oracle文档

如果两个或多个独立定义的缺省方法冲突,或者缺省方法与抽象方法冲突,则Java编译器会产生编译器错误。 您必须显式覆盖超类型方法。

所以基本上,如果你在子类中调用超类中的方法,除非使用super.function()否则你将无法调用超类方法。 在这里阅读更多内容

它是主要的面向对象编程(又名OOP) - 多态。 狗,猫,大象都是动物。

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

它一定不在乎,永远是对的。 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM