static修饰成员变量——自动生成学号方式一
(1)定义一个私有成员变量来接收 自增静态成员变量
使用:所有构造方法中:this.私有成员变量 = ++静态成员变量
public class Student {
private String name;
private int age;
private int id; //私有成员变量接收计数器
static int idCounter; //学号计数器
public Student() {
this.id = ++idCounter; //空参构造
}
public Student(String name, int age) {
this.name = name;
this.age = age;
this.id = ++idCounter; //全参构造
}
public void show() {
System.out.println("姓名为:" + this.name + ",年龄为" + age + ",学号为" + id);
}
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;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
public class Demo {
public static void main(String[] args) {
Student stu1 = new Student("李大伟", 20);
stu1.show();// 姓名为:李大伟,年龄为20,学号为1
Student stu2 = new Student();
stu2.setName("周小姐");
stu2.setAge(18);
System.out.println("姓名为:" +stu2.g