Static and Non-Static Methods
I sometimes stumble between the definition and usage of the
static
keyword in java for classes and methods. Hence, these are my notes on this topic.A good way to look at it is through an example with the code below:
MyPublicInt.java
1public class MyPublicInt {
2 int mValue = 0;
3
4 static MyPublicInt createInt() {
5 return new MyPublicInt();
6 }
7
8 MyPublicInt factoryInt() {
9 return new MyPublicInt();
10 }
11}
The non-static class MyPublicInt can define either static or non-static methods as shown above.
sol_102.java
1public class sol_102 {
2 class MyPrivateInt {
3 int mPrivateValue;
4
5 MyPrivateInt createInt() {
6 return new MyPrivateInt();
7 }
8 }
9
10 // This method can be called from static void main()
11 public static MyPublicInt Solution102a() {
12 MyPublicInt myPublicInt = MyPublicInt.createInt();
13 return myPublicInt;
14 }
15
16 // This method can be called from static void main()
17 public static MyPrivateInt Solution102b() {
18 // This following statement is not allowed
19 MyPrivateInt myPrivateInt = new MyPrivateInt(); // NOT ALLOWED!
20 return myPrivateInt;
21 }
22
23 public static MyPublicInt Solution102c() {
24 // This following statement is not allowed
25 MyPublicInt myPublicInt = MyPublicInt.factoryInt(); // NOT ALLOWED!
26 return myPublicInt;
27 }
28
29 public MyPrivateInt Solution102d() {
30 MyPrivateInt myPrivateInt = MyPrivateInt.createInt(); // NOT ALLOWED!
31 return myPrivateInt;
32 }
33
34 public MyPrivateInt Solution102e() {
35 MyPrivateInt myPrivateInt = new MyPrivateInt();
36 return myPrivateInt;
37 }
38}
We have two MyInt classes created. One as a public class MyPublicInt and another as an inner class MyPrivateInt.
The idea is to create an instance of the class using a static factory method from either of the MyInt class.
The method Solution102a which is static, can create an instance of the MyPublicInt by calling its static method
createInt()
. This is valid because MyPublicInt is not a static class, as it is residing outside of the sol_102 static class.A static method can only access static data members and static methods of another class. It is not able to access non-static methods and variables. A static method is able to rewrite the values of any static data member. This is because the memory of a static method is fixed in ram. We do not need to the instance of its class.
The only way to call a non-static method from a static method, is to have an instance of the class containing the non-static method. Hence, from the static method Solution_102c(), we are not able to call the non-static method
factoryInt()
directly.