static 靜態(tài)變量和靜態(tài)方法
/**
* 測試static 靜態(tài)變量和靜態(tài)方法 隨類加載到方法區(qū)內(nèi)
* 靜態(tài)初始化塊
*/
public class TestStatic {
? ?int id;
? ?String name;
? ?static String country = "China";
? ?//static變量 靜態(tài)變量屬于類 不屬于對象 new的對象不具有country屬性
? ?public TestStatic(int id, String name) {
? ? ? ?this.id = id;
? ? ? ?this.name = name;
? ? ? ?//右鍵generate constructor 生成構(gòu)造方法
? ?}
? ?void aaa(){}
? ?public static void where(){
? ? ? ?//void 無返回值
? ? ? ?System.out.println(country);
? ? ? ?//static方法內(nèi)可以調(diào)用static變量或static方法
? ? ? ?//static方法屬于類,類方法調(diào)用類對象不用再定義country直接使用
? ? ? ?//普通方法aaa屬于對象,類方法無法調(diào)用
? ? ? ?//this屬于對象,類方法也無法調(diào)用
? ?}
? ?public static void main(String[] args) {
? ? ? ?TestStatic u1 = new TestStatic(01,"li");
? ? ? ?TestStatic.where();
? ? ? ?//調(diào)用static方法即類方法,輸入類名.方法名()
? ? ? ?u1.aaa();
? ? ? ?//u1指向?qū)ο笳{(diào)用aaa方法,對象.方法名()
? ? ? ?TestStatic.country = "CN";
? ? ? ?//靜態(tài)變量可修改
? ? ? ?TestStatic.where();
? ?}
}
class TestStatic2{
? ?static String country;
? ?static {
? ? ? ?//語句塊外加static 靜態(tài)初始化塊 在類加載時(shí)執(zhí)行
? ? ? ?System.out.println("類的初始化操作執(zhí)行中");
? ? ? ?country = "China";
? ? ? ?//調(diào)用類變量country
? ? ? ?where();
? ? ? ?//調(diào)用類方法where
? ?}
? ?public static void where(){
? ? ? ?System.out.println(country);
? ?}
? ?public static void main(String[] args) {
? ? ? ?//main方法空
? ?}
}