【问题标题】:java overriding concept of method over ridingjava覆盖方法覆盖的概念
【发布时间】:2015-05-13 22:20:22
【问题描述】:

这里给狗对象提供动物引用的目的是什么..我们可以通过为狗类创建对象来直接访问该方法,请澄清

 class Animal{

 public void move(){
 System.out.println("Animals can move");
 }
 }

class Dog extends Animal{

  public void move(){
  super.move(); // invokes the super class method
  System.out.println("Dogs can walk and run");
 }
}

public class TestDog{

public static void main(String args[]){

 Animal b = new Dog(); // Animal reference but Dog object
 b.move(); //Runs the method in Dog class


 }
}

【问题讨论】:

    标签: overriding


    【解决方案1】:
    class Dog extends Animal
    

    代码 sn-p 的作用

    它使 Animal 类成为 Dog 的父类。 由于 Dog 类继承了 Animal 类,Animal 类成为 Dog 类的父类。

    在创建对象时

    如果你只想使用 Dog 的属性,那么 Dog 作为 对象的类型就足够了。

    Dog b = new Dog();
    

    如果要使用 Animal 和 Dog 的属性,则使用 Animal 作为对象的类型。

    Animal b = new Dog();
    

    这就是为什么 Animal 对象可以用作 引用 Dog 对象。

    【讨论】:

      【解决方案2】:

      你看到 Animal 类是 Dog 类的父类。

      我们在将基类的属性共享给派生类(应用于狗的动物属性)的情况下使用这个概念

      所以 move 的一个属性是 Base 类中的一个方法,可以在 Dog 类中派生,并使用它的属性。

      我们可以使用或构建它 - 方法重载。

      @Override 注解可以使用 - 但可选

      为基类类型的派生类(获得基类及其自身类的功能)创建对象。

      所以基本上它(基类)像核心一样工作,(派生类)像实现一样工作。

      希望对你有帮助。

      【讨论】:

      • 如果我的回答有用且正确,请采纳,让其他人更愿意知道
      猜你喜欢
      • 1970-01-01
      • 2016-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-28
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多