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); }
};
4 Answers. Show activity on this post. Use the interface to define the variable of your class private Foo fi instead of private FooImpl fi , using interfaces over concrete types is the key for good encapsulation and for loose coupling your code. Remove all calls to override methods that are present in your constructor.
Yes, as mentioned we can call all the members of a class (methods, variables, and constructors) from instance methods or, constructors.
In Java, method overriding occurs when a subclass (child class) has the same method as the parent class. In other words, method overriding occurs when a subclass provides a particular implementation of a method declared by one of its parent classes.
Constructors are called only once at the time of the creation of the object.
If you really want to do this, create a secondary private setter method that is called by both the constructor and the public setter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With