I am trying to use a static constructor like the following:
public static DataManager() { LastInfoID = 1; }
and getting this error:
access modifiers are not allowed on static constructors
I would like to know what's my problem.
No, we cannot define a static constructor in Java, If we are trying to define a constructor with the static keyword a compile-time error will occur. In general, static means class level. A constructor will be used to assign initial values for the instance variables.
1. Static constructor is called before the first instance of class is created, wheras private constructor is called after the first instance of class is created. 2. Static constructor will be executed only once, whereas private constructor is executed everytime, whenever it is called.
A static class can only contain static data members, static methods, and a static constructor.It is not allowed to create objects of the static class. Static classes are sealed, means you cannot inherit a static class from another class. Syntax: static class Class_Name { // static data members // static method }
Static constructor runs once per AppDomain just before you access the instance of class first time. You can use it to initialize static variables. On the other hand default constructor runs every time you create new instance of the class. in default constructor you can initialize non-static fields of the instance.
The static constructor has no access modifier: it is just:
static DataManager() // note no "public" { LastInfoID = 1; }
This is because it is never called explicitly (except perhaps via reflection) - but is invoked by the runtime; an access-level would be meaningless.
The problem is that the LastInfoID
field or property is not declared as static in your class and you can access only static members from a static constructor. Also remove the public
keyword from the declaration:
static DataManager() { LastInfoID = 1; }
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