java Static

package java08;

public class Student {
    private String name;//姓名
    private int age;//年龄
    private int id;//学号
    static String room;//教室
    private static  int idCounter = 0;//学号计数器,每当new了一个新对象的时候,计数器++

    public Student() {
        this.id = ++idCounter;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
        this.id = ++idCounter;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
package java08;
//如果一个成员变量使用了static关键字,那么这个变量不在属于对象自己,而是属于所在类。多个对象共享同一份数据

public class DemoStaticField {
    public static void main(String[] args) {
        Student one = new Student("小明",18);
        one.room = "101教室";
        System.out.println("姓名:"+one.getName()+",年龄" + one.getAge()+",教室 "+one.room +",学号"+one.getId());
        Student two = new Student("小红",19);
        System.out.println("姓名:"+two.getName()+",年龄" + two.getAge()+",教室 "+two.room+",学号"+two.getId());
    }
}
//姓名:小明,年龄18,教室 101教室,学号1
//姓名:小红,年龄19,教室 101教室,学号2
原文地址:https://www.cnblogs.com/spp666/p/11715516.html