在java中更改引用对象
我从tutorialspoint.com获得的这些代码让我感到困惑在java中更改引用对象,java,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(){
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
类扩展了Animal
。这意味着,狗拥有动物所有的属性和方法。您还可以有一个类Cat,它扩展了Animal
。所以在实践中,如果你有一堆类似的类,你就不必一遍又一遍地写同样的代码
出现编译错误是因为Animal不知道bark()做什么,而Dog知道Animal中的所有方法/属性。正如前面提到的“每只狗都是动物,但不是每只动物都是狗”。嗯,听起来很有逻辑。要理解所有这些,你还应该阅读多态性的概念。阅读本文和继承概念将使事情变得非常清楚。这里是一个起点@MaizerePathak.Nepal: