问题
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); }
};
回答1:
If you really want to do this, create a secondary private setter method that is called by both the constructor and the public setter.
回答2:
I think that initialising the data members directly in the constructor is better practice. If you call a method, then you have to go look at that method implementation to verify that it really is doing what it looks like it's doing. If you assign to a data member directly, you know that the initialisation is taking place. So in your code:
class A {
private double x, y;
public A() {
x = 0;
y = 0;
}
// ...
}
A constructor should usually be simple, deterministic, and obviously correct. Direct assignment satisfies these goals.
回答3:
A better way to create an object that needs to have lots of different fields set during construction is to use the Builder Pattern.
Rather than duplicate the efforts of others, I will just point you to a most excellent SO answer on this topic.
If the problem is that you need to override setters during the constructor, you can create a hierarchy of Builders instead of, or in addition to, the hierarchy of the primary class that you're trying to build.
来源:https://stackoverflow.com/questions/6104262/java-overridable-call-in-constructor