publicclassMain{ publicstaticvoidmain(String[] args){ Person ming = new Person("Xiao Ming", 12); Person hong = new Person("Xiao Hong", 15); ming.number = 88; System.out.println(hong.number); hong.number = 99; System.out.println(ming.number); } }
publicinterfacePerson{ // 编译器会自动加上public statc final: int MALE = 1; int FEMALE = 2; }
编译器会自动把该字段变为public static final类型。
练习
给Person类增加一个静态字段count和静态方法getCount,统计实例创建的个数。
1 2 3 4 5 6 7 8 9 10 11 12 13
publicclassMain{
publicstaticvoidmain(String[] args){ // TODO: 给Person类增加一个静态字段count和静态方法getCount,统计实例的个数 Person p1 = new Person("小明"); System.out.println(Person.getCount()); // 1 Person p2 = new Person("小红"); System.out.println(Person.getCount()); // 2 Person p3 = new Person("小军"); System.out.println(Person.getCount()); // 3 }