The SuperClass constructor invocation statement, super, is processed before the new instance of Test class has been created. For that reason, the arguments to the superclass constructor invocation statement can not legally refer to members that have not been created and initialized. These include: - Instance variables declared in this class or any superclass. - Instance methods declared in this class or any superclass. - The keyword this.
Legal references include: - Static variables declared in the subclass class or any superclass. - Static methods declared in the subclass or any superclass. So, all we have to do is make instanceVariable static.
I don't think so. You just need to add a super(int i) before other constructors of subclass Test. These codes failed to compile because it lacks the default constructor of super class,which prevent the object of superclass to get a new instance. Plz correct me if I made a wrong reply
hi, As most of you suggested we cannot access the instance variable of a sub class in the constructor of superclass because till the constructor of the super class returns the instance variables are not executed.
JLS 8.8.5 says Finally, if the constructor invocation statement is a superclass constructor invocation and the constructor invocation statement completes normally, then all instance variable initializers of C and all instance initializers of C are executed.
I'm not sure of the answer, probably has something to do with the var not being static, but I don't think it has anything to do with the missing constructor in the last post because I beleive the default constructor is always implied even if not written. Please correct me if I'm wrong
Joined: Jan 04, 2003
hi Damien humm..... In this case If you declear a constructor in that class,the compiler would not give a free gift (default one) to you in the same class,so you need to write an another one in that class. Anyway,Thomas may be worry about something which lead him to neglect writting the constructor.
Joined: May 05, 2000
I don't need a default constructor in the SuperClass because the constructor is always getting invoked by the constructors of its child class. In fact, adding a default consructor to the SuperClass does not get rid of the error. You can't have a super(1) and a this(1) in the same constructor so that doesn't help either. Changing Test() to run super() doesn't help because the Test(int i) is also getting an error. As some wrote, the underlying error is that you can not use an instance variable in an explicit constructor invocation using this() or super(). The rule is that the arguments in an explicit constructor invocation (this(myVar) or super(myVar)) are executed in a static context. If myVar does not exist in a static context then you can't use myVar as an argument. What would exist in a static context? Either myVar is static or myVar is a method variable.
[ April 22, 2003: Message edited by: Thomas Paul ]