class Demo7_Static {
public static void main(String[] args) {
//System.out.println("Hello World!");
Person p1 = new Person(); //创建对象
p1.name = "White";
p1.speak(); //White...null,虽然静态,但还未赋值
p1.country = "America";
p1.speak(); //White...America
/*
* a:随着类的加载而加载
* b:优先于对象存在
* c:被类的所有对象共享
共性用静态,特性用非静态
*/
Person p2 = new Person();
p2.name = "Sunny";
//p2.country = "Canada";
p1.speak(); //White...America
p2.speak(); //Sunny...America
Person.country = "China"; //静态多了一种调用方式,类名.变量名
System.out.println(Person.country);
/*
Person.name = "Day"; //无法从静态上下文中引用非静态变量,必须先创建对象
System.out.println(Person.name);
*/
}
}
class Person{
String name; //姓名
//String country;
static String country; //国籍
public void speak() { //说话
System.out.println(name + "..." + country);
}
}
|
|