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

Static constructor  RSS feed

 
Santosh Kumar Nekkanti
Greenhorn
Posts: 8
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hai,
      I want to use a static constructor .Ofcourse, there may not be any use ,but i want to use it . It is showing compile time error "modifier static not allowed here" when running the following program.

I am expecting when the "r" object of class "Rama" is being instantiated at line6 and the constructor should be called.But why it is not happening? And how it can be syntactically wrong?


class Rama{
public static Rama(){
System.out.println("Rama");
}
public static void main(String [] args){
Rama r=new Rama(); //line 6

}
}

Thanks,
Santosh N.
 
amit punekar
Ranch Hand
Posts: 544
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
The "static" keyword signifies that the operation or variable is available at class level. This means it will be shared by all the class instances i.e. objects.
The constructor is for creating/initializing a new instance of the class and is called when you perform a "new" construct. Owning to this fact it cannot be declared as static as it is directly related to the instance of a class.

Hope this helps.

Regds,
Amit
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is showing compile time error "modifier static not allowed here" when running the following program.

That looks explicit enough to me.

From 8.8.3 Constructor Modifiers :
Unlike methods, a constructor cannot be abstract, static, final, native, strictfp, or synchronized
 
Santosh Kumar Nekkanti
Greenhorn
Posts: 8
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes Amit,
         I got it now,Since the constructor will be every time invoked whenever an object related to that class is being instantiated,several copies of it will be created within a class ,but static method should have only one instance per class . Thank you very much.
 
Campbell Ritchie
Marshal
Posts: 55745
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
by the way: your non-breaking spaces will look a lot better with ; characters. Not &nbsp but   I have added the ;s for you.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!