Java可重写的调用构造函数 [英] Java overridable call in constructor
问题描述
我知道这是一个糟糕的(安全)实践,从Java中的对象构造函数调用可覆盖的方法。但是,例如,如果构造函数必须初始化一些数据,调用相应的setter方法似乎是合理的,这样我就不会复制代码。设置器是公共的,不是最终的。有没有什么标准的方法来处理这个,就像声明私有setter方法,公共的调用?下面是一些代码:
I know it is a bad (security) practice to call overridable methods from an object constructor in Java. However, for example, if the constructor has to initialize some data, it seems reasonable to call the respective setter method so that I don't copy code. The setters are public and not final. Is there any standard way of dealing with this, like declaring private setter methods, that the public ones call? To illustrate, here is some code:
class A {
private double x,y;
private privateSetX(double x1) { x=x1; }
private privateSetY(double y1) { y=y1; }
public A() { privateSetX(0); privateSetY(0); }
public setX(double x1) { privateSetX(x1); }
public setY(double y1) { privateSetY(y1); }
};
推荐答案
为此,创建一个由构造函数和公共设置器调用的辅助私有setter方法。
If you really want to do this, create a secondary private setter method that is called by both the constructor and the public setter.
这篇关于Java可重写的调用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!