gpt4 book ai didi

java - 构造后如何执行子类继承的initialize方法?

转载 作者:行者123 更新时间:2023-11-30 06:38:49 24 4
gpt4 key购买 nike

考虑以下代码:

public abstract class Command {

public Command() {
configure();
}

public void configure() {
}

}


public abstract class ComplexCommand extends Command {

private ArrayList<String> commands = new ArrayList<>();

@Override
public void configure() {
System.out.println(commands);
}

}

configure() 方法旨在由 Command 或 ComplexCommand 的子类实现,以便修改命令的属性,因此预期的功能是执行 configure() 方法在实现子类中被构造之后(commands 变量已经被初始化)。但是,在此示例中调用 new ComplexCommand() 会导致将 null 打印到控制台。如果我错了,请纠正我,但这似乎是因为子类构造函数中隐含的 super() 在初始化子类字段之前执行。

以下是如何使用这些类的示例:

public class MyTestCommand extends Command {

@Override
public void configure() {
setUsage("Usage: /test <target>");
setDescription("This is a test command");
}

}

经过尝试,我确实找到了一种解决问题的方法,但我想知道是否有人有更好的解决方案。我的修复方法是通过创建一个允许启用/禁用从父级执行 configure() 的构造函数来覆盖父级构造函数,然后从子级运行它。

public abstract class Command {

public void configure() {
}

public Command() {
configure();
}

protected Command(boolean configure) {
if (configure) {
configure();
}
}

}

public abstract class ComplexCommand extends Command {

private ArrayList<String> commands = new ArrayList<>();

@Override
public void configure() {
System.out.println(commands);
}

public ComplexCommand() {
super(false);
configure();
}

}

在此示例中,configure() 在子类的字段初始化并显示 [] 后正确运行。不管怎样,它看起来仍然很老套,一开始可能会令人困惑。除了我所做的之外,还有更好的方法吗?

最佳答案

在我看来,这整个想法是有缺陷的,因为您只是使用配置方法作为子构造函数的替代品。无论如何它都没有用。

为什么首先需要配置?所以子类可以覆盖你所说的。但他们已经可以重写构造函数了,那还有什么意义呢?

public abstract class Command {   

public Command() {
// Do things to initialize Command
}
}

public abstract class ComplexCommand extends Command {

private ArrayList<String> commands;

public ComplexCommand() {
super();
// Do things to initialize ComplexCommand
this.commands = new ArrayList<>();
System.out.println(this.commands);
}
}

public class MyTestCommand extends Command {

public MyTestCommand() {
super();
setUsage("Usage: /test <target>");
setDescription("This is a test command");
}
}

关于java - 构造后如何执行子类继承的initialize方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44753681/

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