Java static关键字 桃扇骨 2022-05-22 00:11 185阅读 0赞 **未使用static** class Test { private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Test(int age) { super(); this.age = age; } }; public class Static { public static void main(String[] args) { // TODO Auto-generated method stub Test t1 = new Test(10); System.out.println(t1.getAge()); Test t2 = new Test(11); System.out.println(t2.getAge()); } } //运行结果 10 11 **使用static** class Test { static int age; //全局有效 public int getAge() { return age; } public static void setAge(int age) { //必须声明static Test.age = age; //用类名的方式 } public Test(int age) { super(); Test.age = age; } }; public class Static { public static void main(String[] args) { // TODO Auto-generated method stub Test t1 = new Test(10); Test t2 = new Test(11); Test.age = 5; //用类名调用 System.out.println(t1.getAge()); System.out.println(t2.getAge()); } } //运行结果 5 5
还没有评论,来说两句吧...