繁体   English   中英

在Java中创建接口对象

[英]Creating interface objects in java

我遇到了一些Java代码:

public class LocationProvider {

   public interface LocationCallback {
      public void handleNewLocation(Location location);
   }

   // class constructor
   public LocationProvider(Context context, LocationCallback callback){ 
      ...
   }
}

在Java中,我第一次遇到构造函数或方法,该构造函数或方法的参数为接口的“类型”。 是否可以创建接口的对象? 您可以像普通对象一样使用它们吗?

在C ++中,我知道不可能创建抽象类的对象。

您永远不会创建“作为接口的类”的对象。 您可以创建实现该接口的类的对象,然后将该对象作为参数传递给需要接口类型实参的方法。

好。 让我们回顾一下基础知识:)。

class A implements X{// where X is an interface
}

class B implements X{
}

现在,我们有

void someMethodAcceptingInterfaceX(X someInstanceOfX)
{
//do something
}

现在可以了

X a = new A();
X b = new B();
someMethodAcceptingInterfaceX(a);
someMethodAcceptingInterfaceX(b);

即,您可以传递接口X的任何内容 任何实现接口的类都被称为该接口的实例 (在更广泛的上下文中)。

您正在将引用的类型与引用的对象的类型混淆。

到底是怎么回事

将类实例化为object ,并具有给定类型的引用是两件事:

  • 实际上,您无法实例化接口。 这意味着:

    • 您不能调用new MyInterface()
    • 任何对象都不会具有MyInterface类型(请记住,我在这里谈论的是对象,而不是对其的引用)。
  • 相反, 引用可以具有与其引用的对象类型相同的任何类型。 给定类型的超类型为:

    • 对象类的所有超类
    • 由对象的类或其父类实现的所有接口

      这称为类型的多重继承。

另一种查看方式:

  • 接口无法实例化
  • 但是接口是有效类型

在代码中,这意味着:

MyInterface i; // This is valid, only says that the type of i is MyInterface
i = new MyInterface(); // This is not valid, cannot instantiate the interface

您可以在此处了解引用类型和对象类型之间的区别。

举个例子,使用Integer类,它扩展了Number类并实现了Serializable类:

Integer i = new Integer(1); // The object referenced by i is of type Integer, forever
                            // i is a reference to that object,
                            // its type is a reference to Integer
Number n = i; // Now n is also referencing the same object.
              // The type of n is a reference to a Number. 
              // The referenced object hasn't changed, its type is still Integer
              // This is possible because Number is a supertype of Integer

Serializable s = i;  // Same, s is now referencing the same object.
                     // The object is still the same, its type hasn't changed
                     // The type of s is a reference to a Serializable.
                     // This is possible because Serializable is a supertype of Integer

适用于您的案例

构造函数定义

public LocationProvider(Context context, LocationCallback callback)

要求第二个参数是对LocationCallback的引用。

这并不意味着所引用的对象应该属于该类型,实际上这是不可能的。 这仅意味着传递的引用应该是LocationCallback的子类型,最终引用其类型是实现LocationCallback的类的对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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