我试图创建对任意对象的方法引用,因此定义了以下类型:
interface I {
boolean get(Impl impl);
}
static class Impl {
public boolean get() {
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我声明了方法引用,如下所示:
I i = Impl::get;
Run Code Online (Sandbox Code Playgroud)
当我打电话时:
i.get(null);
Run Code Online (Sandbox Code Playgroud)
我得到了NullPointerException:
Exception in thread "main" java.lang.NullPointerException
Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么即使没有在Impl任何地方使用参考文件也会发生这种情况吗?
我正在学习有关如何使用this()重载的构造函数,并遇到了以下限制:
您不能在调用this()时使用构造函数类的任何实例变量。
例如:
class Test{
int x;
public Test() {
this(x); //Does not compile
}
public Test(int y) {}
void method1() {
method2(x); //OK
}
void method2(int y) {}
}
Run Code Online (Sandbox Code Playgroud)
我知道不需要将实例字段传递给构造函数,因为默认情况下它是可见的。但是,为什么相同的限制不适用于实例方法?