Day10-static静态(1)
在cn.itcast.day10.demo03包下有一个学生类Student,有一个测试类Demo001StaticField
学生类Student:
public class Student { private int id; private String name; private int age; static String room; public static int idCounter = 0; public Student() { idCounter++; } public Student(String name, int age) { this.id = ++idCounter; this.name = name; this.age = age; } 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; } }
定义五个变量:
1、ID
2、姓名
3、年龄
4、教室
5、ID计数器,用于自动计算学号(还未学习public关键字)
说明:当类中的变量使用static关键字修饰以后,那么这样的内容不再属于对象自己,而是属于类,凡是本类的对象,都共享同一份。
static测试类:
public class Demo001StaticField { public static void main(String[] args) { Student one = new Student("郭靖", 19); one.room = "101教室"; System.out.println("姓名:" + one.getName() + ", " + "年龄:" + one.getAge() + ", " + "教室:" + one.room + ", " + "学号:" + one.getId()); Student two = new Student("黄蓉", 16); System.out.println("姓名:" + two.getName() + ", " + "年龄:" + two.getAge() + ", " + "教室:" + two.room + ", " + "学号:" + two.getId()); } }
定义一个对象one并赋值姓名和年龄,然后对Student类中的room赋值”101教室”,随后输出对象one,其中room输出为”101教室”,ID自动计数为1。
定义一个对象two并赋值姓名和年龄,然后输出对象two,其中room依然输出为”101教室”,ID自动计数为2。
说明该内容”101教室”属于Student类,而不是对象one。