简体   繁体   English

在Java中更改参考对象

[英]Changing the reference object in java

I got these code that have confused me from tutorialspoint.com 我从tutorialspoint.com获得了这些让我感到困惑的代码

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 bark(){
      System.out.println("Dogs can bark");
   }
}

 public class TestDog{

   public static void main(String args[]){
      Animal a = new Animal(); // Animal b has reference an object of  type animal class
      Animal b = new Dog(); // Animal reference but Dog object how??

      a.move();// runs the method in Animal class
      b.move();//Runs the method in Dog class
      b.bark();
   }
 }

Animal reference to dog object is working ..I dont understand why is that working .Need to know the underlying concept behind it. 动物对狗对象的引用正在起作用。.我不明白为什么该起作用。需要了解其背后的潜在概念。 Also if Animal reference to dog object is possible why not Dog reference to Animal not possible? 同样,如果可以用动物引用狗的对象,为什么不能用狗引用动物呢? like: 喜欢:

public class TestDog{

   public static void main(String args[]){
      Animal a = new Dog(); // Animal b has reference an object of  type animal class
      Dog b = new Animal(); //now this leads to an error

      a.move();
      b.move();

   }
 }

It shows error during compilation 编译时显示错误

Inheritance is the main concept behind it. 继承是其背后的主要概念。 Read about it anywhere and you will get the idea. 随时随地阅读有关内容,您将得到灵感。

Generally, the case in the last code snippet is: every dog is an animal, but not every animal is a dog. 通常,最后一个代码段中的情况是:每只狗都是动物,但并非每只动物都是狗。 Just like in real life. 就像现实生活中一样。

As you can see the class Dog extends Animal . 如您所见,Dog类extends Animal What this means is, that Dog has all attributes and methods animal has. 这意味着,狗具有动物具有的所有属性和方法。 You could also have a class Cat which extends Animal . 您还可以使用extends Animal Cat类。 So in practice you won't have to write the same code over and over again, if you have a bunch of similar classes. 因此,实际上,如果您有一堆类似的类,则不必一遍又一遍地编写相同的代码。

You get the compilation error because Animal has for example no idea what bark() does, while Dog knows about all methods/attributes in Animal. 您会收到编译错误,因为例如Animal不知道bark()会做什么,而Dog知道Animal中的所有方法/属性。 As already mentioned "every dog is an animal, but not every animal is a dog". 如前所述,“每只狗都是动物,但并非每只动物都是狗”。

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

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