【问题标题】:Clarification about overriding in Java关于 Java 中覆盖的说明
【发布时间】:2016-03-19 07:14:45
【问题描述】:

以此为例:

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 对象优先何时被 Animal 类型引用?

我注意到许多网站并没有解释这一点,而是直接抛出示例而不逐行讨论。只是想澄清我的术语混乱。

附带说明,是否可以有一个 Dog 对象但调用 Animal 类下的 move() ?例如有类似的东西:

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

这可能吗? ((Animal) doggy).move() 会做到这一点吗?

【问题讨论】:

  • 另外使用@Override 表示法,它可以防止你犯错误,比如在子类中拼错方法名。

标签: java terminology overriding


【解决方案1】:

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

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

public class Dog extends Animal {

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

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

          ((Animal) doggy).move()

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

【讨论】:

    【解决方案2】:

    你可以这样做

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        来自oracle docs

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

        所以基本上,如果您在子类中调用超类中的方法,则除非您使用super.function(),否则您将无法调用超类的方法。 Read up more on it here

        【讨论】:

          【解决方案5】:

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

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

          它必须不在乎,总是对的。 :)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-08-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-12-28
            • 1970-01-01
            相关资源
            最近更新 更多