Previously saw a technology Daniel wrote a static and non-static members, static and non-static methods of the respective differences, feel very good, write a small program here to illustrate these differences.
Package com.ljy.chapter5;/** * This program would demonstrate the use of the static method. * @author LIAO Jianya * */public class statictest{public static void Main (string[] args) {System.out.println ("Call non-static method with Object") ; MyObject obj = new MyObject (); Obj.print1 (); System.out.println ("Invoke static method with Class"); Myobject.print2 ();//You can call the static method directly with the class name}}class myobject{private static string str1 = "Staticproperty";p rivate string str2 = " Nonstaticproperty ";p ublic MyObject () {}public void Print1 () {System.out.println (STR1);// A non-static method can access the static domain System.out.println (str2);//non-static method can access the nonstatic domain Print2 ();//non-static method can access the static method}public the Statics void Print2 () { System.out.println (STR1);//static method can access static domain //system.out.println (str2); Static methods do not have access to non-static domain//print1 ();//static methods cannot access non-static methods }}
Output Result:
Calling a non-static method with an object Staticpropertynonstaticpropertystaticproperty calls a static method with a class Staticproperty
If you remove the comment symbol in the Blue comment section, you will get two error:
Error 1 caused when the first comment is removed:
static reference to the non-static field str2
Error 2 After the second comment is removed:
static reference to the non-static method Print1 () from the type MyObject
Conclusion: Static methods cannot access non-static member variables, and static methods cannot access non-static methods.
In fact, it is a sentence: static can not access non-static, but not static access to static and can be accessed non-static.
At the same time: static methods can be called directly through the class name, without object invocation, thus reducing the cost of instantiation.
The application of static and the difference between statics and non-static