Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Says cannot reference f before supertype constructor has been called

 
Prashanth Muthyala
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Test19 {
float f;
Test19(){
this(f); //I did not get this line....
f = 3;
}
Test19(float f){
System.out.println(f);
}
public static void main(String args[]) {
Test19 t = new Test19();
}
}
 
Nathaniel Stoddard
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically, a class's instance variables can't be accessed until all the parent constructors have done their thing .. so obviously, you can't send an instance variable as an argument to a parent constructor since it isn't really there yet.
 
Animesh Shrivastava
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prashant,
Its not giving the error as u said, its saying "Cannot refer to an instance field f while explicitly invoking a constructor"
An instance field belongs to an instance. So, i guess before creating an instance u are trying to use the instance field, thats why the error props up.

But u can use a static field as that belongs to a class
like this is true:
public class Test19 {
static float f;
Test19(){
this(f); //No error here
f = 3;
}
Test19(float f){
System.out.println(f);
}
public static void main(String args[]) {
Test19 t = new Test19();
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic