![](/img/trans.png)
[英]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.