Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

constructors  RSS feed

 
Kondapally Ashwin
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

For the following code :
public class Test19 {
float f;
Test19(){
this(f);
f = 3;
}
Test19(float f){
System.out.println(f);
}
public static void main(String args[]) {
Test19 t = new Test19();
}
}

I am getting a compiler error that "cannot reference f before super type constructor has been called" for the statement this(f).

Please help me in understanding this.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

The short answer is that you can't mention any of the members of a class in a constructor until after any call to "this" or "super".

Here you're passing the member "f" to the other constructor of this class, which will print "f". You're essentially trying to trick Java into displaying the value of "f" before your object is initialized, and Java doesn't want to do that! What are you trying to do, anyway?
 
Kondapally Ashwin
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the prompt reply.

This was a question I came across.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!