gpt4 book ai didi

java - 如何在构造函数的 super() 方法调用中使用子类变量 (this) 初始化其他类?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:47:22 25 4
gpt4 key购买 nike

我正在尝试构建一个类库,我可以在未来的 Swift 游戏项目中使用这些类(只需进行最少的代码调整),这些类将用于创建更适合我正在处理的当前项目的子类。但是,我在构造函数的 super() 方法调用中使用“this”初始化其他类时遇到了问题。这是代码形式的问题:

public class App extends JFrame {
public App(AppRunner appRunner, AppPanel appPanel) {
this.appRunner = appRunner;
this.appPanel = appPanel;
}
}


public class Pong extends App {
public App() {
super(new AppRunner(10, this), new AppPanel(this));
}
}

这会发送一个与在类初始化之前使用“this”变量相关的错误。

我考虑过在 App 类中使用抽象方法并让子类实现它们,但我决定不喜欢那样。计划(代码形式):

public abstract class App extends JFrame {

public App() {
this.appRunner = initializeAppRunner();
this.appPanel = initializeAppPanel();
}

abstract AppRunner initializeAppRunner();

abstract AppPanel initializeAppPanel();
}

我还测试了一种使用一点泛型和反射(我对此知之甚少)的方法。我也不喜欢这个,因为我不能很容易地更改类的构造函数参数。以下是我当前的代码:

public class App extends JFrame {
public App(Class<? extends AppRunner> appRunnerClass, Class<? extends AppPanel> appPanelClass) {
try {
this.appRunner = appRunnerClass.getConstructor(Integer.class, App.class).newInstance(10, this);
this.appPanel = appPanelClass.getConstructor(App.class).newInstance(this);
} catch (Exception e) {
e.printStackTrace();
}
add(appPanel);
}
}

public class Pong extends App {
public Pong() {
super(AppRunner.class, PongPanel.class);
}
}

我想我想知道他们是否有更简单的方法来做到这一点,或者我是否应该使用泛型/抽象方法示例。

最佳答案

刚刚使用的任何问题:

public Pong() {
appRunner = new AppRunner(10, this);
appPanel = new AppPanel(this);
}

———

您可以将 lambda 函数传递给 App 构造函数,允许您自定义实用程序类的创建,但让 App 父类(super class)创建这些类。

参见 Function interface .

class App extends ... {
App( Function<App, AppRunner> runner_creator,
Function<App, AppPanel> panel_creator) {
appRunner = runner_creator.apply(this);
appPanel = panel_creator.apply(this);
}

class Pong extends App {
Pong() {
super(
app -> new PongRunner(10, app),
app -> new PongPanel(app));
}
}

您正在将 lambda 函数(没有任何 this 引用)传递给父类(super class),因此派生类控制实用程序类的创建方式以及使用的特定类。

注意:这些实用程序类是使用父类(super class)的 this 引用构造的,它是一个 App,而不是派生类类型。

关于java - 如何在构造函数的 super() 方法调用中使用子类变量 (this) 初始化其他类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50575994/

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