Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java overridable call in constructor

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); }
};
like image 754
K.Steff Avatar asked May 23 '11 23:05

K.Steff


People also ask

How do I fix an overridable constructor call?

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.

Is it OK to call methods in constructor?

Yes, as mentioned we can call all the members of a class (methods, variables, and constructors) from instance methods or, constructors.

What is an overridable method in Java?

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.

Can you call a constructor multiple times in Java?

Constructors are called only once at the time of the creation of the object.


1 Answers

If you really want to do this, create a secondary private setter method that is called by both the constructor and the public setter.

like image 107
Nathan Ryan Avatar answered Sep 28 '22 06:09

Nathan Ryan