day08-静态static关键字修饰成员变量

This commit is contained in:
2026-07-22 15:27:35 +08:00
parent 5202e64a57
commit d65bb8793a
2 changed files with 44 additions and 0 deletions
@@ -0,0 +1,25 @@
package com.inmind.static02;
/*
static关键字的使用:
可以修饰成员变量和成员方法。
1.使用static修饰成员变量的使用方式:只跟类有关,与对象无关了,并且该类的每个对象都共享了该变量的值
静态变量的使用方式:
a.类名.静态变量名(推荐使用)
b.对象名.静态变量名(不推荐使用)
*/
public class StaticDemo10 {
public static void main(String[] args) {
//创建2个学生对象
Student s1 = new Student("张三");
Student s2 = new Student("李四");
//问张三同学,你们在哪个教室上课???
s1.show();
//告诉张三,你们在1903上课
Student.classRoom = "1903";//正确写法
//s1.classRoom = "1903";//不推荐的写法
//问李四同学,你们在哪个教室上课???
s2.show();
}
}
@@ -0,0 +1,19 @@
package com.inmind.static02;
public class Student {
String name;
int age;
int id;
static String classRoom; //(静态变量)教室,但是教室只有一个,学生有n个,n个学生都使用同一个教室
public Student() {
}
public Student(String name) {
this.name = name;
}
public void show() {
System.out.println("姓名:"+name+""+classRoom+"教室上课");
}
}