java - 如何在构造函数的 super() 方法调用中使用子类变量 (this) 初始化其他类?
问题描述
我正在尝试构建一个类库,可以在未来的 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 超类创建这些类。
见函数界面。
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
引用)传递给超类,因此派生类控制实用程序类的创建方式以及使用的特定类。
注意:这些实用程序类是使用超类的this
引用构造的,它是一个App
,而不是派生类类型。
推荐阅读
- javascript - node.js 获取构造被拒绝的承诺的位置
- c# - 将 ASP.NET Core(完整的 .net 框架)与旧的 .Net Framework 2.0 代码混合
- laravel - 在 Laravel 中修复 Vue Flash 消息
- c# - 如何在调试模式下禁用 serilog
- spring - 在spring boot中从文件系统加载properties.yaml文件
- abap - 根据 RICEF,BAPI 是接口还是转换工具?
- sql - VB.NET > 如何使用 Using 语句插入图像并检索它以显示?
- javascript - 如果导航栏打开,则添加过渡到背景颜色更改
- r - 如何生成并非所有数字都取 0 - 9 的 5 位随机整数?
- php - PHP - 即使在代码已更正后仍包含错误