Does anyone know why you can reference a static method in the first line of the constructor using this() or super(), but not a non-static method?
Consider the following working:
public class TestWorking{
private A a = null;
public TestWorking(A aParam){
this.a = aParam;
}
public TestWorking(B bParam)
{
this(TestWorking.getAFromB(bParam));
}
//It works because its marked static.
private static A getAFromB(B param){
A a = new A();
a.setName(param.getName());
return a;
}
}
And the following Non-Working example:
public class TestNotWorking{
private A a = null;
public TestNotWorking(A aParam){
this.a = aParam;
}
public TestNotWorking(B bParam)
{
this(this.getAFromB(bParam));
}
//This does not work. WHY???
private A getAFromB(B param){
A a = new A();
a.setName(param.getName());
return a;
}
}
Non-static methods are instance methods. This are only accessible in existing instance, and instance does not exist yet when you are in constructor (it is still under construction).
Why it is so? Because instance methods can access instance (non-static) fields, which can have different values in different instances, so it doesn’t make sense to call such method on something else than existing, finished instance.