day08--静态static关键字修饰成员方法

This commit is contained in:
xx
2026-09-22 14:53:32 +08:00
parent fe7909e12b
commit 4973afbd21
2 changed files with 42 additions and 0 deletions
+27
View File
@@ -0,0 +1,27 @@
package com.inmind.static02;
/*
static关键字的使用:
可以修饰成员变量和成员方法。
1.使用static修饰成员变量的使用方式:只跟类有关,与对象无关了,并且该类的每个对象都共享了该静态变量的值
静态成员变量的使用方式:
a.类名.静态变量名(推荐使用)
b.对象名.静态变量名(不推荐使用)
*/
public class Demo08 {
public static void main(String[] args) {
//创建2个学生(同班同学)
Student s1 = new Student("张三", 20);
Student s2 = new Student("李四", 21);
//你们在哪个教室上课??
System.out.println(Student.clazz);
System.out.println(s1.clazz);
//告诉张三,你们今天上课的教室是1903室
s1.clazz = "1903室";
//遇到李四,你知道今天的教室在哪吗??
System.out.println(s2.clazz);
Student s3 = new Student("王五", 20);
System.out.println(s3.clazz);
Student.clazz = "1904";//修改静态变量
}
}
@@ -0,0 +1,15 @@
package com.inmind.static02;
public class Student {
String name;
int age;
static String clazz;//班级
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}