JAVA static关键字
static成员变量
public class Person { String name; static int age; Person() { System.out.println("Person 无参构造"); } void eat() { System.out.println("Person 吃饭"); } }
也可以通过类名方式调用
public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Person person1 = new Person(); Person person2 = new Person(); person1.age = 12; System.out.println(person1.age); System.out.println(person2.age); Person.age = 13; System.out.println(person1.age); System.out.println(person2.age); } }
运行结果
Person 无参构造
Person 无参构造
12
12
13
13
static成员函数
静态成员函数只能使用静态成员变量
public class Person { static String name; static int age; Person() { System.out.println("Person 无参构造"); } static void eat() { System.out.println(name + " 在吃饭"); } }
public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Person.name = "furong"; Person.eat(); } }
运行结果
furong 在吃饭