public class staticaaa {
public static void main(String[] args){
Person p1=new Person();
p1.name="张老师";
p1.country="中国";
Person p2=new Person();
p2.name="朴老师";
p1.xingzhi();
p2.xingzhi();
}
}
class Person{
String name;
static String country;
public void xingzhi(){
System.out.println(name+country);
}
}
内存图解:
共性用静态个性用非静态
特点:
随着类的加载而加载
优先于对象存在
被类的所有对象共享
可以通过类名调用也可以通过对象名调用 静态修饰的内容一般称其为:与类相关的,类成员。
注意事项:
在静态方法中是没有this关键字的:
静态是随着类的加载而加载的,this是随着对象的创建而存在的,静态比对象先存在
静态方法只能访问静态成员变量和静态成员方法:
静态方法:
成员变量:只能访问静态成员变量
成员方法:只能访问静态成员方法
非静态方法:
成员变量:可以是静态也可以是非静态
成员方法:可以是静态也可以是非静态
案例演示:
public class st {
public static void main(String[] args) {
demo a=new demo();
a.print();
}
}
class demo{
static int num=10; //静态成员变量
int num1=20; //非静态成员变量
public void print() { //非静态成员方法
System.out.println(num);
System.out.println(num1);
}
/* public static void print1() {
System.out.println(num);
System.out.println(num1);
} 会报错Non-static field 'num1' cannot be referenced from a static context */
}