0
点赞
收藏
分享

微信扫一扫

【Java笔记】静态变量(static关键字)的使用

A邱凌 2022-03-21 阅读 110

static 关键字可以声明“公共”的变量,即同一对象中所有实例的属性值相同的属性,这样的公共属性,我们声明为静态变量或者类变量(static)

目录

static 的使用范围

实例变量与静态变量的区分

实例变量(无 static)

静态变量(有 static)

static 修饰属性的其他说明

static 修饰静态方法

static 使用中的注意点

代码举例


static 的使用范围

static 可以用来修饰、属性、方法、代码块、内部类

实例变量与静态变量的区分

实例变量(无 static)

我们创建了类的多个对象,每个对象都独立的拥有一套类中的非静态属性。当修改其中一个对象中的非静态属性时,不会导致其他对象中同样的属性值修改。

静态变量(有 static)

我们创建了类的多个对象,多个对象共享同一个静态变量。当通过某一个对象修改静态变量时,会导致其他对象调用此静态变量时,是被修改过的值。

static 修饰属性的其他说明

1. 静态变量随着类的加载而加载,可以通过 “类 . 静态变量” 的方式进行调用

2. 静态变量的加载要早于对象的创建

3. 由于类只会加载一次,则静态变量在内存中也只会存在一份,存在方法区的静态域中

4. 静态变量的生命周期大于实例变量

静态变量(类变量)实例变量
可以调用不可以调用
对象可以调用可以调用

static 修饰静态方法

1. 静态变量随着类的加载而加载,可以通过 “类 . 静态方法” 的方式进行调用

2. 

静态方法非静态方法
可以调用不可以调用
对象可以调用可以调用

3. 静态方法中,只能调用静态的方法或属性

   非静态方法中,既可以调用非静态的方法或属性,也可以调用静态的方法或属性

static 使用中的注意点

在静态的方法内,不能使用 this 关键字、super 关键字

关于静态属性和静态方法的使用,可以从生命周期的角度去理解

代码举例

public class StaticTest {
	public static void main(String[] args) {
	food.cate = "中国美食";
	food f = new food("北京烤鸭");
	System.out.println(f.getId());
	f.eat();
	food f1 = new food("重庆火锅");
	System.out.println(f1.getId());
	f1.show();
	}
}
class food{
	String name;
	private int id;
	public static int init = 1; // 利用静态属性初始化变量
	static String cate;
	
	public food() {
		id = init++; 
	}
	public food(String name) {
		this();
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void eat() {
		System.out.println(this.name + "很好吃");
		// 调用非静态结构
		this.ingredient();
		// 调用静态结构
		cook();
	}
	public static void show() {
		System.out.println(food.cate + "享誉世界");
		// 不能调用非静态结构 Cannot make a static reference to the non-static method eat() from the type food
		// eat(); 
		// 可以调用静态结构
		System.out.println(food.cate);
		cook();
	}
	public void ingredient() {
		System.out.println("美食需要细致的材料");
	}
	public static void cook() {
		System.out.println("美食需要精致的烹饪");
	}
}

>>> 1
    北京烤鸭很好吃
    美食需要细致的材料
    美食需要精致的烹饪
    2
    中国美食享誉世界
    中国美食
    美食需要精致的烹饪
举报

相关推荐

0 条评论