I have the next code:
class Foo {
public Foo (String param) { ... }
}
class Bar extends Foo {
public Bar () {
super (doSmth());
...
}
private static String doSmth () {
//what I can NOT do here?
}
}
I wonder is it safe? Are there any limitations about doSmth method?
The simple rule is do not access, directly or indirectly, the “this” object from within a constructor.
That means you should not call overrideable methods from a constructor, nor should you call a method that calls an overrideable method, or call a method that calls a method that calls an overrideable method, or … you get the idea.
It also means that you should not pass “this” to anything, as the other thing could call an overrideable method.
In your particular case what you have is fine. If it were to change to:
Then you would have a (potential) problem because doSmth could call an overriden method in subclass of Bar that relies on data that hasn’t been initialized yet.
Here is an example of what could happen:
So, as long as you don’t call any overridden methods you are good. However it is safest to just follow the “rule” of never passing this outside of the constructor and never invoking overrideable (non-final) methods, directly or indirectly from a constructor.