上这个类
public abstract class Mother{
public class Embryo{
public void ecluse(){
bear(this);
}
}
abstract void bear(Embryo e);
}
我只有在拥有Mother实例的情况下才能创建Embryo实例:
new Mother(){...}.new Embryo().ecluse();
问题:
最佳答案
嵌套类Embryo
在static
中隐式地为interface
。
因此,它无权访问实际上可调用的方法bear
,该方法与Mother
接口(interface)的实例有关。
所以:
Mother
声明为interface
,然后您的Embryo
的ecluse
方法就无法虚拟调用bear
,因为它是静态范围内的Mother
保留为abstract class
,但是需要Mother
的实例(匿名或子类的实例)才能获得Embryo
的实例(但除非另有说明,否则Embryo
是实例范围的,并且可以虚拟地调用bear
)自包含示例
package test;
public class Main {
public interface MotherI {
// this is static!
public class Embryo {
public void ecluse() {
// NOPE, static context, can't access instance context
// bear(this);
}
}
// implicitly public abstract
void bear(Embryo e);
}
public abstract class MotherA {
public class Embryo {
public void ecluse() {
// ok, within instance context
bear(this);
}
}
public abstract void bear(Embryo e);
}
// instance initializer of Main
{
// Idiom for initializing static nested class
MotherI.Embryo e = new MotherI.Embryo();
/*
* Idiom for initializing instance nested class
* Note I also need a new instance of `Main` here,
* since I'm in a static context.
* Also note anonymous Mother here.
*/
MotherA.Embryo ee = new MotherA() {public void bear(Embryo e) {/*TODO*/}}
.new Embryo();
}
public static void main(String[] args) throws Exception {
// nothing to do here
}
}