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;
}
}
Yes, as mentioned we can call all the members of a class (methods, variables, and constructors) from instance methods or, constructors.
You can not call an instance method in the static method directly, so the Instance method can be invoked using an object of the class.
The invocation of a constructor constructs a new object of the class to which the constructor belong and returns a reference to the created object. The object is constructed by making use of the parameters passed to the constructor. Example: new String("test")
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.
See the Java Language Specification 8.8.7.1. This states that
An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods or inner classes declared in this class or any superclass, or use
this
orsuper
in any expression; otherwise, a compile-time error occurs.
This is because you can not call an instance method before the instance is created. By the way, it is possible to call an instance method later on in the constructor (although not a solution for you).
I think its's because final instance variables are not set yet (so you have no instance yet) and an instance method could access one. Whereas all static initialization has been done before the constructor call.
Greetz, GHad
because when you calling this or super in constructor your object is not constructed yet. (your instance is not initialized completely yet). so calling an instance method doesn't make scene.
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