Java note (7) Application of static keywords, static keywords
Import java. util. enumeration; class Dog {static int legNum; int age; public static void walk () {// eat (); // The instance variable legNum = 4 cannot be accessed in the class method; // class method: System. out. println (legNum + "walking leg! "); // Age = 6; // instance variables cannot be accessed in class methods} public void eat () {walk (); // The metadata class method age = 6 in the instance method; // instance variables can only be accessed in the instance method; System. out. print ("dog" + age + "years old! "); System. out. println (legNum +" walking leg! "); // Attributes of the category class can be found in the instance method} public class TestStaticVariable {public static void main (String [] args) {Dog. walk (); // use the Class Name of the walk method to directly access Dog huanhuan = new Dog (); huanhuan. eat (); // The eat method must be accessed through the Instance Object Name huanhuan }}
Running result:
4-legged walk!
4-legged walk!
Dog 6 years old! 4-legged walk!