static关键字

static关键字
  • 作用:是一个修饰符,用于修饰成员(成员变量,成员方法)
  • 1、被static修饰后的成员变量只有一份
  • 2、当成员被static修饰后,多了一种访问方式,处理可以对象调用之外,还可以被类直接调用(类名. 静态成员)

static的特点:

  • 随着类的加载而被加载
  • 优先于对象的存在
  • 被所有对象所共享的
  • 可以直接被类名所调用

存放位置

  • 类变量随着类的加载而存在于data内存区
  • 实例变量随着对象的建立而存在于堆内存
public class test_static {
	public static void main(String[] args){
		Student6 A = new Student6();
		A.country = "中国";
		Student6 B = new Student6();
		System.out.println(B.country);
		System.out.println(Student6.country); //可以类名直接调用静态变量
	}
}

class Student6{
	String name;
	int age; //实例变量
	static String country; //静态变量(类变量)
}

在这里插入图片描述

静态方法
  • 静态方法只能访问静态成员
  • 非静态的方法既能访问静态的成员(成员变量,成员方法),也能访问非静态成员
  • 静态的方法中不可以定义this super 关键字,因为静态优先于对象存在,所以静态方法不可以出现this
public class test_static1 {
	public static void main(String[] args){
		whale3 A = new whale3();
		A.descrip();
		A.descrip1();
	}
}

class whale3{
	String name;
	static int age;
	static void descrip(){
		System.out.println(age);
	}
	static void descrip1(){
		String address = "冰岛"; //局部变量不能用static修饰
		System.out.println(address);
	}
}
什么时候使用静态成员
  • 当属同一个类的所有对象出现共享数据时,可以用static修饰这个成员变量
什么时候使用静态方法
  • 当功能内部没有访问到非静态的成员时(对象特有的数据),那么该功能可以定义成静态的
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章