Static applications and static and non-static applications
Previously, I saw a technical master who wrote a story about the differences between static and non-static members, static and non-static methods. I think it is quite good to write a small program here to illustrate these differences.
Package com. liaojianya. chapter5;/*** This program will demonstrate the use of static method. * @ author liao jianya **/public class StaticTest {public static void main (String [] args) {System. out. println ("calling non-static methods with objects"); MyObject obj = new MyObject (); obj. print1 (); System. out. println ("calling static methods with classes"); MyObject. print2 () ;}} class MyObject {private static String str1 = "staticProperty"; private String str2 = "nonstaticProperty"; public MyObject () {} public void print1 () {System. out. println (str1); // a non-static method can access the static domain System. out. println (str2); // The non-static method can access the non-static domain print2 (); // The non-static method can access the static method} public static void print2 () {System. out. println (str1); // The static method can access the static domain // System. out. println (str2); // The static method cannot access non-static domain // print1 (); // The static method cannot access non-static method }}
Output result:
Call the non-static method staticPropertynonstaticPropertystaticProperty using an object call the static method staticProperty using a class
If the annotation is removed from the annotation, two errors are reported:
Error 1 caused by removing the first comment:
Cannot make a static reference to the non-static field str2
Error 2 caused by the removal of the second comment:
Cannot make a static reference to the non-static method print1() from the type MyObject
Conclusion: static methods cannot access non-static member variables. Static methods cannot access non-static methods.
It is actually a sentence: static users cannot access non-static ones, but non-static users can access static ones and non-static ones.
At the same time, the static method can be called directly through the class name without calling the object, thus reducing the overhead of Instantiation.