gpt4 book ai didi

java - 模板方法需要在子构造函数中声明一个对象

转载 作者:行者123 更新时间:2023-12-02 07:36:59 24 4
gpt4 key购买 nike

扩展母类的子类,在其构造函数中调用在子类中实例化的模板方法,因为它需要在子构造函数中获取值。

我怎样才能做这样的事情,而不改变我的父构造函数(Foo,在这里。我不能在真正的 Foo 类中做任何改变):

public abstract class Foo{
public Foo(){
register();
}

public abstract void register();

public void aMethod(int aValue){
// body
}

}

public class Bar extends Foo{

public Foo(int aValue){
// body
}

register(){
aMethod(aValue);
}
}

在这里,即使我将 aValue 放入字段中,aValue 也不会被创建

aMethod(aValue);.

如何解决我的问题?

我正在寻找任何模式、ULM、解决方案。

最佳答案

a child class extending a mother class which, in its constructor call a template method instianted in the child class because it need a value obtained in the child constructor.

为什么子类构造函数不简单地将值传递给父类(super class)构造函数?

public abstract class Foo {
protected Foo(int value) {
... use value ...
}
}

public class Bar extends Foo {
public Foo(int value) {
super(value);
}
...
}

请注意,在构造函数中调用虚方法是一种危险的做法,因为子类还没有机会初始化自身。

关于java - 模板方法需要在子构造函数中声明一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12078355/

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