JDK 1.8版本
//主类
public class DemoStudent {
public static void main(String[] args) {
Student stu1 = new Student("tianxin",24);
Student.classroom = "101教室";
Student stu2 = new Student("java",11);
System.out.println("学号="+stu1.getId()+",姓名="+stu1.getName()
+",年龄="+stu1.getAge()+",班级="+Student.getClassroom());
System.out.println("学号="+stu2.getId()+",姓名="+stu2.getName()
+",年龄="+stu2.getAge()+",班级="+Student.getClassroom());
}
}
//Student学生类
public class Student {
private int id; // 学号 自动生成
private String name; // 姓名
private int age; // 年龄
public static String getClassroom() {
return classroom;
}
static String classroom; //注意 这里如果赋值了 在主程序中无法修改 所以不要赋值
private static int count = 0; // 每次new一个新的对象 count++
public Student() {
count = count + 1;
this.id = count;
}
public Student(String name, int age) {
this.name = name;
this.age = age;
count = count + 1;
this.id = count;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = 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;
}
}