[英]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.