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

This commit is contained in:
2026-01-20 16:29:29 +08:00
parent 71c2e2049d
commit d15ea0c281
2 changed files with 46 additions and 0 deletions

View File

@@ -0,0 +1,26 @@
package com.inmind.static02;
/*
static关键字的使用
可以修饰成员变量和成员方法。
1.使用static修饰成员变量的使用方式只跟类有关与对象无关了,并且该类的每个对象都共享了该变量的值
静态成员变量的使用方式:
a.类名.静态变量名(推荐使用)
b.对象名.静态变量名(不推荐使用)
*/
public class Demo10 {
public static void main(String[] args) {
//创建2个学生对象
Student s1 = new Student("张三", 18, 1);
Student s2 = new Student("李四", 18, 1);
//遇到s1学生问你上课的教室是哪一个
// System.out.println(s1.clazz);
System.out.println(Student.clazz);
// s1.clazz = "1903室";
Student.clazz = "1903室";
//遇到s2学生问你上课的教室是哪一个
System.out.println(s1.clazz);
Student s3 = new Student();
System.out.println(s3.clazz);
}
}

View File

@@ -0,0 +1,20 @@
package com.inmind.static02;
public class Student {
//成员变量 (每个对象单独拥有)
String name;
int age;
int id;
//静态变量(每个对象共享)
static String clazz;//教室这种变量一个修改了所有对象的内容都要改就应该用static
public Student(String name, int age, int id) {
this.name = name;
this.age = age;
this.id = id;
}
public Student() {
}
}