static的概念
static修飾的特點
- 被類的所有對象共享,這也是我們判斷是否使用靜态關鍵字的條件
- 可以通過類名調用當然,也可以通過對象名調用【推薦使用類名調用】
示例代碼
class Student {
public String name; //姓名
public int age; //年齡
public static String university; //學校 共享資料!是以設計為靜态!
public void show() {
System.out.println(name + "," + age + "," + university);
}
}
public class StaticDemo {
public static void main(String[] args) {
// 為對象的共享資料指派
Student.university = "大學";
Student s1 = new Student();
s1.name = "林青霞";
s1.age = 30;
s1.show();
Student s2 = new Student();
s2.name = "風清揚";
s2.age = 33;
s2.show();
}
}
static通路特點
非靜态的成員方法
- 能通路靜态的成員變量
- 能通路非靜态的成員變量
- 能通路靜态的成員方法
- 能通路非靜态的成員方法
靜态的成員方法
總結成一句話就是