首先介绍一个static关键字的例子
先建一个Person类
用static修饰”国家“
public class Person {
public String name;
public static String country;
}
然后测试一下这个类
public class MyTest {
public static void main(String[] args) {
Person person = new Person();
person.name = "张三";
person.country = "美国";
System.out.println("---------------");
Person person2 = new Person();
person2.name = "李四";
person2.country = "新加坡";
System.out.println("---------------");
Person person3 = new Person();
person3.name = "王五";
person3.country = "英国";
System.out.println(person.name + "----" + person.country);
System.out.println(person2.name + "----" + person2.country);
System.out.println(person3.name + "----" + person3.country);
}
}
结果
张三----英国
李四----英国
王五----英国
造成这个结果的原因下面讲,我们先说下static关键字的概念
static关键字的特点
a:随着类的加载而加载
b:优先于对象存在
c:被类的虽有对象共享
d:可以通过类名调用
static关键字的注意事项
a:在静态方法中是没有this关键字的
因为静态是随着类的加载而加载,this是随着对象的创建而存在的,而静态比对象先存在(下面通过内存图形象解释)
静态方法只能访问静态的成员变量和静态的成员方法
简单来说,静态只能访问静态,动态可以访问静态和动态
下面我们通过内存图,详细解释下开始的那个例子
由static创建的变量随着类储存在方法区的静态区,也就是共享区,在此区域的变量是共享的,所以静态变量country随着类名调用里面储存的数据也会变化。