javaSE之static关键字

static也是javaSE重要的关键字之一。它的作用主要体现在以下两方面:

static类属性

我们还是先看一段代码,之前没有static时,我们的代码是这样的:
先定义一个类:

public class Person{
	private String name ;
	private int age ;
	public Person(String name, int age) {
		this.name = name ;
		this.age = age ;
	}
	public void getInfo() {
		System.out.println("姓名:"+this.name+",年龄:"+this.age) ;
	}
}

上面是之前我们就会写的一个类,假如现在我要实例化两个对象:

public class Test {
	public static void main(String[] args){
		Person per = new Person("张三",19) ; 
		per.getInfo() ;
		Person per1 = new Person("李四",20) ;
		per1.getInfo() ;
	}
}

这时候我们看看它在内存中的地址是怎样存储的:
在这里插入图片描述
那么现在我们在这个类中加一个静态属性也就是类属性:
代码:

public class Person{
	private String name ;
	private int age ;
	static String country = "中国";//类属性
	public Person(String name, int age) {
		this.name = name ;
		this.age = age ;
	}
	public void getInfo() {
		System.out.println("姓名:"+this.name+",年龄:"+this.age) ;
	}
}

那么这个时候,这个country属性在内存中还是在堆上吗?答案是否定的,我们在学习C语言的时候知道啦在我们的内存当时还有一块区域叫做全局变量区也叫静态区,在java里面也是有全局数据区的,我们看看上面的代码在内存中如何存储的:
在这里插入图片描述
我们会看到country这个属性并不在堆上存储了,而是在全局数据区,因为它的属性名前面加了static关键字,这就是static的类属性。

之前我们没有static修饰时,所有的非静态属性都必须在实例化之后才可以使用,但是static属性并不受实例化的控制,因为所有的对象对于静态属性都指向的是同一块区域,并且是共享的,这就意味着当你改变一个对象的静态属性时,其他的也会跟着改变
如果你理解不了,我们还是拿刚才的代码举个例子:

public class Person{
	private String name ;
	private int age ;
	static String country = "中国";//类属性
	public Person(String name, int age) {
		this.name = name ;
		this.age = age ;
	}
	public void getInfo() {
		System.out.println("姓名:"+this.name+",年龄:"+this.age+",国家:"+this.country) ;
	}
}
public class Test {
	public static void main(String[] args){
		Person per = new Person("张三",19) ; 
		per.country="中华民国";
		per.getInfo() ;
		Person per1 = new Person("李四",20) ;
		per1.getInfo() ;
	}
}

在这里插入图片描述
我们会发现,我们只改变了per的country属性,但是per1的这个属性也变了,这就是static类属性的特点。
注意:在访问静态属性是,应该是类名.属性名

定义类时,如何选择实例变量和类属性呢?

  • 在定义类时,99%的情况都不会考虑static属性,以非static属性(即实例变量)为主
  • 如果需要描述共享属性的概念,或者不受对象实例化控制,使用static

static 类方法

刚才是static类属性,在属性前面加上static关键字,那么static类方法就是在方法前面加上static关键字。
还是看代码吧:

public class Person{
	private String name ;
	private int age ;
	static String country ;//类属性
	public Person(String name, int age) {
		this.name = name ;
		this.age = age ;
	}
	public static void setCountry(String c){//类方法
		country = c ;
	}
	public void getInfo() {
		System.out.println("姓名:"+this.name+",年龄:"+this.age+",国家:"+this.country) ;
	}
}
public class Test{
	public static void main(String[] args) {
		Person.setCountry("中国");
		Person person = new Person("张三",20);
		person.getPersonInfo();
	}
}

上面的setCountry就是一个类方法,你可以看看这个格式,前后不能颠倒,我们在访问静态方法的时候同样是类名.方法名。需要注意以下两点:

1.所有的静态方法都不允许调用非静态的属性和方法
2.所有非静态方法允许访问静态方法或者属性。

这个其实也好理解,我们把它定义成静态的就是希望它是公用的,但它公用归公用,不能影响了我的私有属性和方法的权限。

main方法的static

这样以来你就很容易理解了为什么main方法是static的了?
首先,以我们平时写代码的习惯也可以说是哪里需要给哪里,也就意味着它是一个公用的方法了
最重要的一点就是它不受实例化的限制,因为我们用main方法一开始并不知道是哪个类要用,根本无需实例化。

猜你喜欢

转载自blog.csdn.net/qq_40550018/article/details/84309327