gpt4 book ai didi

java - 如何在接口(interface)中实现嵌套的非静态类?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:24:57 26 4
gpt4 key购买 nike

有这门课

public abstract class Mother{
public class Embryo{
public void ecluse(){
bear(this);
}
}
abstract void bear(Embryo e);
}

只有当我有一个 Mother 实例时,我才能创建一个 Embryo 实例:

new Mother(){...}.new Embryo().ecluse();

问题:

  • 如何将 Mother 定义为接口(interface)?

最佳答案

嵌套类 Embryointerface 中是隐式的 static

因此,它无法访问虚拟可调用方法 bear,该方法属于您的 Mother 接口(interface)的实例。

因此:

  • 要么你将 Mother 声明为 interface,那么你的 Embryoecluse 方法实际上不能调用 bear 因为它是静态范围的
  • 或者,您将Mother 保留为抽象类,但需要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
}
}

关于java - 如何在接口(interface)中实现嵌套的非静态类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35065038/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com