static(静态)
需求:描述一下传智学生类。 都是中国人….
目前存在的问题: 所有的学生都是中国的,有n个学生就会有n份中国的数据存内存中,这样子会浪费内存。
目前方案: 把“中国”这个数据移动 到数据共享区中,共享这个数据给所有的Student对象使用即可。
问题2: 如何才能把这个数据移动 到数据共享区中共享呢?
解决方案: 只需要使用static修饰该数据即可。
静态的成员变量只会在数据共享区中维护一份,而非静态成员变量的数据会在每个对象中都维护一份的。
内存分析原理图:
以上需求的实现:
class Student{
String name;
//使用了static修饰country,那么这时候country就是一个共享的数据。
static String country = "中国"; //国籍
//构造函数
public Student(String name){
this.name = name;
}
}
class Demo9 {
public static void main(String[] args){
Student s1 = new Student("张三");
Student s2 = new Student("陈七");
s1.country = "小日本";//若注释掉该句,下边输出的都是“中国”;若添加上该句,下边输出的都是“小日本”。
System.out.println("姓名:"+s1.name+" 国籍:"+ s1.country); // 中国
System.out.println("姓名:"+s2.name+" 国籍:"+ s2.country); // 小日本
}
}
static(静态\修饰符)
static修饰成员变量 :
如果有数据需要被共享给所有对象使用时,那么就可以使用static修饰。
静态成员变量的访问方式:
- 方式1: 可以使用对象进行访问。
格式: 对象.变量名。
- 方式2: 可以使用类名进行访问。
格式: 类名.变量名;
注意:
- 1、非静态的成员变量只能使用对象进行访问,不能使用类名进行访问。
- 2、千万不要为了方便访问数据而使用static修饰成员变量,只有成员变量的数据是真正需要被共享的时候才使用static修饰。
static修饰成员变量的应用场景:
如果一个数据需要被所有对象共享使用的时候,这时候即可好实用static修饰。
static修饰成员函数:(见“java基础知识22_静态函数”)
练习1:
class Student{
String name; //非静态成员变量
static String country = "中国"; //静态的成员变量
public Student(String name){
this.name = name;
}
}
class Demo10 {
public static void main(String[] args){
Student s1 = new Student("狗娃");
System.out.println("国籍:"+ Student.country);//类名.country这句正确,因为定义country时使用了static修饰
System.out.println("国籍:"+ s1.country);//对象.country这句正确,因为定义country时使用了static修饰
System.out.println("名字:"+ Student.name);//类名.name这句会报错,因为定义name时没有使用static修饰
System.out.println("名字:"+ s1.name);//对象.name这句正确,非静态变量可以用对象.变量名
}
}
练习2:
需求: 统计一个类被使用了多少次创建对象,该类对外显示被创建的次数。
class Emp{
//非静态的成员变量。
static int count = 0; //计数器
String name;
//构造代码块
{
count++;
}
public Emp(String name){
this.name = name;
}
public Emp(){ //每创建一个对象的时候都会执行这里 的代码
}
public void showCount(){
System.out.println("创建了"+ count+"个对象");
}
}
class Demo11{
public static void main(String[] args){
Emp e1 = new Emp();
Emp e2 = new Emp();
Emp e3 = new Emp();
e3.showCount();
}
}