接口的引用可以= null 吗?
我刚才在一本书上读到了这段代码。
public class AdapterWrapper implements ListAdapter {
ListAdapter delegate=null;
// other code
}
ListAdapter
是一个公共接口,该接口的引用已被创建并分配为 null。这是有效的吗?我对此真的很困惑。
I read this code in a book just now.
public class AdapterWrapper implements ListAdapter {
ListAdapter delegate=null;
// other code
}
The ListAdapter
is a public interface and a reference of that interface has been made and assigned null. Is this valid? I'm really confused by this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这是有效的。它只是意味着
delegate
是对ListAdapter
接口的引用,并且它当前指向null
。您稍后可以将其指向实现
ListAdapter
接口的任何类,例如SimpleCursorAdapter
、WrapperListAdapter
或任何其他你想要的实施。当您提前不知道运行时它将是什么类时,使用接口类型作为参考非常有用。因此,您只需使用指向接口的引用即可。
Yes, it's valid. It just means that
delegate
is a reference toListAdapter
interface and it's currently pointing atnull
.You can later make it point to any class implementing the
ListAdapter
interface, such asSimpleCursorAdapter
,WrapperListAdapter
or any other implementation you want.Using an interface type as reference is useful when you don't know ahead of time what class is it going to be at runtime. So you just use a reference pointing to an interface.
变量有一个值,该值是空引用。这没有什么问题。
任何引用类型变量的值要么是对某些兼容类型的实例的引用,要么是 null - 这对于类和接口都是相同的。
The variable has a value, which is a null reference. There's nothing problematic about this.
The value of any reference type variable is either a reference to an instance of some compatible type, or null - that's the same for both classes and interfaces.
只是在这里引用维基百科上的 Interface(Java) :
所以根据这个定义,代码似乎是有效的。
Just quoting Wikipedia on Interface(Java) here:
So the code seems valid by this definition.