PackageCOM.WANGCF; Public classTest {String name= "Hello"; StaticString sex= "Male"; Test T=NewTest (); /*** Static methods can be called directly in the same class static members, but not directly call non-static members * If you want to invoke a non-static variable in a static method, you can access the non-static variable by creating the object of the class, and then through the object*/ Public Static voidprint () {test test=NewTest ();//Create objects of this classSYSTEM.OUT.PRINTLN (name);//error here, non-static variable cannot be called in static methodSystem.out.println (Test.name);//non-static variables can be accessed through objects of the class itselfSystem.out.println (t);//You can't call t here either .SYSTEM.OUT.PRINTLN (Sex);//Static variables can be called directly in a static method } /*** Static variables and non-static variables can be called at the same time in normal member methods*/ Public voidShow () {System.out.println (name); SYSTEM.OUT.PRINTLN (Sex); System.out.println (T.name); } /*** Non-static methods cannot be called directly in static methods, and non-static methods need to be accessed through objects *@paramargs*/ Public Static voidMain (string[] args) {t.show (); Show (); //non-static methods cannot be called directlyTest test=NewTest (); Test.show (); Print (); //non-static methods can be called directly }}
Static variable statics in Java