Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
关于Java中重写的澄清_Java_Terminology_Overriding - Fatal编程技术网

关于Java中重写的澄清

关于Java中重写的澄清,java,terminology,overriding,Java,Terminology,Overriding,以此为例: 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 voi

以此为例:

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
>>>

这可能吗?(动物)doggy.move()是否可以完成此任务?

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

比如:super.move()在这种情况下,将调用父函数。

如果两个或多个独立定义的默认方法冲突,或者默认方法与抽象方法冲突,那么Java编译器将生成编译器错误。必须显式重写超类型方法


因此,基本上,如果您在子类中调用超类中的方法,您将无法调用超类的方法,除非您使用
super.function()

你可以这样做

    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
类下的“
move()
方法”已经覆盖了
Animal
类下的“
move()
”方法

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

public class Dog extends Animal {

   public void move(){
     super.move();
   }
}
对于第三个问题,答案是“不”


这是简单的“冗余”,并在
Dog
类下提供输出“
move()

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

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

它一定不在乎,永远正确。:)

此外,使用@Override表示法还可以防止犯错误,比如在子类中拼写错误的方法名。
Animal d = new Dog();
Animal c = new Cat();
Animal t = new Tiger()