[英]Which Java language mechanisms allow object reference variable types to be different than the type of object it refers to?
[英]Java object reference mechanisms
我有點堅持以下問題:
兩種Java語言機制允許對象引用變量的類型與它引用的對象的類型“不同”? 舉例說明。 在什么意義上他們沒有什么不同?
我目前的答案是“實施”和“延伸”對嗎? 它們是相似的,因為它們都會創建一個類,至少會擁有超類的所有方法簽名,可以是實際的,抽象的或接口。 它是否正確? 提前致謝!
這或多或少是正確的。 你的答案的第二部分應該討論子類型。 在Java中,對象僅具有相同的方法簽名是不夠的。 實際上必須有一個聲明的子類型關系(通過extends / implements)。
這不僅僅是迂腐。 在某些語言(但不是Java)中,僅僅存在兼容的方法簽名就足以實現類型兼容性。 這被稱為“鴨子打字”。
器物
interface Animal {
void attackHuman(); // actually public abstract by default
}
class Horse implements Animal {
public void attackHuman() { }; // must implement
}
// type and reference the same
Horse a1 = new Horse();
// type and reference different
Animal a2 = a1;
擴展
class Animal {
void attackHuman();
}
class Dinosaur extends Animal {
// attackHuman() inherited
}
// type and reference the same
Dinosaur a1 = new Dinosaur();
// type and reference different
Animal a2 = a1;
看這個例子....
- 動物是Super-Class
動物 , 狗和貓是從它inherited
的。
-您可以使用Animal Object Reference Variable
創建Dog對象。
-這被稱為Class Polymorphism
。
public class Test {
public static void main(String[] args){
Animal a = new Dog();
new Hospital().treatAnimal(a);
}
}
class Animal {
public void sayIt(){
}
}
class Dog extends Animal{
public void sayIt(){
System.out.println("I am Dog");
}
}
class Cat extends Animal{
public void sayIt(){
System.out.println("I am Cat");
}
}
See the NEXT PAGE for the Remaining Code
class Hospital{
public void treatAnimal(Animal a){
if(a instanceof Dog){
a.sayIt(); // Will output "I am Dog"
}
else{
a.sayIt(); // Will output "I am Cat"
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.