day08-静态static关键字修饰成员变量
This commit is contained in:
28
day08/src/com/inmind/static02/Demo08.java
Normal file
28
day08/src/com/inmind/static02/Demo08.java
Normal file
@@ -0,0 +1,28 @@
|
||||
package com.inmind.static02;
|
||||
/*
|
||||
static关键字的使用:
|
||||
可以修饰成员变量和成员方法。
|
||||
1.使用static修饰成员变量的使用方式:只跟类有关,与对象无关了,并且该类的每个对象都共享了该变量的值
|
||||
静态成员变量的使用方式:
|
||||
a.类名.静态变量名(推荐使用)
|
||||
b.对象名.静态变量名(不推荐使用)
|
||||
*/
|
||||
public class Demo08 {
|
||||
public static void main(String[] args) {
|
||||
//创建2个学生
|
||||
Student s1 = new Student("张三", 18);
|
||||
Student s2 = new Student("李四", 19);
|
||||
//将教室设置为1903室
|
||||
Student.clazz = "1903室";
|
||||
//遇到学生s1,询问,你的教室是哪里
|
||||
// System.out.println(s1.name + "的教室是" + s1.clazz);
|
||||
System.out.println(s1.name + "的教室是" + Student.clazz);
|
||||
//告诉学生s1,你的教室改为1905室
|
||||
Student.clazz = "1905室";
|
||||
|
||||
//遇到学生s2,询问,你的教室是哪里
|
||||
System.out.println(s2.name + "的教室是" + Student.clazz);
|
||||
|
||||
//注意:静态内容被所有对象共享。
|
||||
}
|
||||
}
|
||||
19
day08/src/com/inmind/static02/Student.java
Normal file
19
day08/src/com/inmind/static02/Student.java
Normal file
@@ -0,0 +1,19 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user