java – 引用类型和对象类型之间的区别?

Java文档说:

When you define a new interface, you are defining a new reference
data type…[]

有些人使用名称“对象类型”来引用用于首先实例化对象实例的类.

因为我们不能使用接口来实例化一个对象,我可以说一个对象永远不会具有该接口的类型,但是如果它实现了那种接口,你可以使用该接口类的引用来访问该对象吗?

维基百科说:

[]… a data type or simply type is a classification identifying one of
various types of data, such as real-valued, integer or Boolean, that
determines the possible values for that type; the operations that can
be done on values of that type; the meaning of the data; and the way
values of that type can be stored.

我没有看到Java中的接口如何确定“该类型的可能值;可以对该类型的值执行的操作;数据的含义;以及可以存储该类型的值的方式.”我的理由是,因为接口没有定义方法可以做什么,所以它们不是数据类型,只有类和基元类型定义数据类型.接口仅定义如果使用引用访问某个数据类型的对象的方式.

基于此,如果有人说实现接口的对象具有相同类型的接口,我可以回答他/她是错的,因为接口只提供引用类型而对象永远不能具有接口类型吗?

最佳答案 你说“实现接口的对象具有相同类型的接口”是正确的.并且由于对象是类的实例,因此技术上从不具有与接口相同的类型,因为接口无法在Java中实例化.接口可以被视为类的蓝图.

我能想到的最常见的实现之一是Java Collections.

Map<Integer, String> mapExample = new HashMap<Integer, String>();

这里的对象类型是HashMap和参考类型的Map(接口). HashMap将继承Map中声明的方法,并提供它们自己的实现.

I don’t see how an interface in Java determines “the possible values for that type; the operations that can be done on values of that type; the meaning of the data; and the way values of that type can be stored.” My reasoning is that, because interfaces don’t define what the methods can do, they aren’t data types and only the classes and primitive types define data types.

让我们通过以下示例解决这个问题:

public interface IHelloWorld {

   public String helloWorld(String world);

}

这里我有一个包含helloWorld方法的接口.我已将访问器类型定义为public,我已确保它将返回一个String类型,它将采用String参数.所以它肯定可以定义方法可以做什么.任何实现此接口的类都需要提供helloWorld的实现细节.如果我要实现这个,我会做以下事情:

public class HelloWorld implements IHelloWorld {

    public String helloWorld(String world) {
        return "Hello " + world;
    }    

}

你可以在这里看到虽然我们在IHelloWorld接口中没有实现细节,但我们定义了helloWorld方法将返回的内容以及该方法将接受的参数类型.

我希望这能为你澄清一些事情.

点赞