Java – 在调用父类构造函数之前设置类属性

huangapple go评论71阅读模式
英文:

Java - Setting Class Properties Before Super

问题

我有以下的类:

public abstract class MyAbstractClass {
     protected int x;
     protected int number;
     public MyAbstractClass(int x) {
         this.x = x;
         this.number = this.generateNumber();
     }
     public abstract int generateNumber(); // 这个方法在超类构造函数和其他地方被调用
}
public class MySubClass extends MyAbstractClass {
     private int y;
     public MySubClass(int x, int y) {
          super(x);
          this.y = y;
     }
     @Override
     public int generateNumber() {
         return this.x + this.y; // this.y尚未被初始化!
     }
}

我的问题是MySubClassy属性在超类构造函数运行之前必须被初始化,因为在超类构造函数中会使用y属性的方法。
我意识到即使使用一些巧妙的方法可能也无法实现这一点,但我尚未找到替代方案。

另外请注意,我将会有更多的派生类,它们的构造函数会传入不同的值。

英文:

I have the follow classes:

public abstract class MyAbstractClass {
     protected int x;
     protected int number;
     public MyAbstractClass(int x) {
         this.x = x;
         this.number = this.generateNumber();
     }
     public abstract int generateNumber(); // This class is called in the super constructor and elsewhere
}
public class MySubClass extends MyAbstractClass {
     private int y;
     public MySubClass(int x, int y) {
          super(x);
          this.y = y;
     }
     @Override
     public int generateNumber() {
         return this.x + this.y; // this.y has not been initialized!
     }
}

My issue is that MySubClass's y property has to be initialized before the super constructor is run, because a method using y is run in the super constructor.
I am aware that this may not be possible even with some sneaky workaround, but I am yet to find an alternative solution.

Also please keep in mind that I will have many more derived classes, with different values being passed into their constructors.

答案1

得分: 4

你可以将数字计算推迟到需要的时候再进行。

public abstract class MyAbstractClass {
    protected int x;
    protected Integer number;

    public MyAbstractClass(int x) {
        this.x = x;
    }

    public int getNumber() {
        if (number == null) {
            number = generateNumber();
        }
        return number.intValue();
    }

    protected abstract int generateNumber();
}
英文:

You can defer the number calculation until it is needed.

public abstract class MyAbstractClass {
	protected int x;
	protected Integer number;

	public MyAbstractClass(int x) {
		this.x = x;
	}

	public int getNumber() {
		if (number == null) {
			number = generateNumber();
		}
		return number.intValue();
	}

	protected abstract int generateNumber(); 
}

huangapple
  • 本文由 发表于 2020年9月29日 13:35:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/64113493.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定