简体   繁体   English

Java对象引用机制

[英]Java object reference mechanisms

I'm kind of stuck on the following question: 我有点坚持以下问题:

What two Java language mechanisms allow the type of an object reference variable to be "different" than the type of the object to which it refers? 两种Java语言机制允许对象引用变量的类型与它引用的对象的类型“不同”? Give specific examples to illustrate. 举例说明。 In what sense are they not different at all? 在什么意义上他们没有什么不同?

My current answer is that it is "implement" and "extend" right? 我目前的答案是“实施”和“延伸”对吗? And they are similar because they both will make a class that at least will posses all of the method signatures of the super class which can be actual, abstract, or an interface. 它们是相似的,因为它们都会创建一个类,至少会拥有超类的所有方法签名,可以是实际的,抽象的或接口。 Is this correct? 它是否正确? Thanks in advance! 提前致谢!

That is more or less correct. 这或多或少是正确的。 The second part of your answer should talk about subtyping. 你的答案的第二部分应该讨论子类型。 In Java, it is not sufficient for objects to just have the same method signatures. 在Java中,对象仅具有相同的方法签名是不够的。 There actually has to be a declared subtyping relationship (via extends / implements). 实际上必须有一个声明的子类型关系(通过extends / implements)。

This is not mere pedantry. 这不仅仅是迂腐。 In some languages (but not Java), the mere existence of compatible method signatures is sufficient for type compatibility. 在某些语言(但不是Java)中,仅仅存在兼容的方法签名就足以实现类型兼容性。 This is called "duck typing". 这被称为“鸭子打字”。

Implements 器物

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;

Extends 扩展

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;

See this example.... 看这个例子....

- Here the Animal is the Super-Class , and the Dog and Cat are inherited out of it. - 动物Super-Class 动物是从它inherited的。

- You can Create a Dog object using an Animal Object Reference Variable . -您可以使用Animal Object Reference Variable创建Dog对象。

- This is known as Class Polymorphism . -这被称为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM