[英]Changing the reference object in java
我从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();
}
}
动物对狗对象的引用正在起作用。.我不明白为什么该起作用。需要了解其背后的潜在概念。 同样,如果可以用动物引用狗的对象,为什么不能用狗引用动物呢? 喜欢:
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();
}
}
编译时显示错误
继承是其背后的主要概念。 随时随地阅读有关内容,您将得到灵感。
通常,最后一个代码段中的情况是:每只狗都是动物,但并非每只动物都是狗。 就像现实生活中一样。
如您所见,Dog类extends Animal
。 这意味着,狗具有动物具有的所有属性和方法。 您还可以使用extends Animal
Cat类。 因此,实际上,如果您有一堆类似的类,则不必一遍又一遍地编写相同的代码。
您会收到编译错误,因为例如Animal不知道bark()会做什么,而Dog知道Animal中的所有方法/属性。 如前所述,“每只狗都是动物,但并非每只动物都是狗”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.