手機wap網(wǎng)站的分析網(wǎng)絡(luò)營銷官網(wǎng)
1.static 修飾符應(yīng)用范圍
static修飾符只能用來修飾類中定義的成員變量、成員方法、代碼塊以及內(nèi)部類(內(nèi)部類有專門章節(jié)進行講解)。
2.static 修飾成員變量
static 修飾的成員變量稱之為類變量。屬于該類所有成員共享。
示例
package cn.lyxq.test04;public class ChinesePeople {private String name;private int age;public static String country = "中國";public ChinesePeople(String name,int age){this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}
}
package cn.lyxq.test04;public class ChinesePeopleTest {public static void main(String[] args) {ChinesePeople cp1 = new ChinesePeople("張三",20);System.out.println(ChinesePeople.country);ChinesePeople.country="日本";ChinesePeople cp2 = new ChinesePeople("李四",30);System.out.println(ChinesePeople.country);ChinesePeople cp3 = new ChinesePeople("王五",32);System.out.println(ChinesePeople.country);}}
如果類變量是公開的,那么可以使用 類名.變量名 直接訪問該類變量
3.static 修飾成員方法
static 修飾的成員方法稱之為類方法,屬于該類所有成員共享。
package cn.lyxq.test04;public class ChinesePeople {private String name;private int age;private static String country = "中國";public ChinesePeople(String name,int age){this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}//類方法public static String getCountry() {return country;}//類方法public static void setCountry(String country) {ChinesePeople.country = country;}
}
package cn.lyxq.test04;public class ChinesePeopleTest {public static void main(String[] args) {ChinesePeople cp1 = new ChinesePeople("張三",20);ChinesePeople.setCountry("日本");ChinesePeople cp2 = new ChinesePeople("李四",30);System.out.println(ChinesePeople.getCountry());ChinesePeople cp3 = new ChinesePeople("王五",32);System.out.println(cp3.getCountry());//不是最優(yōu)訪問方式}}
如果類方法是公開的,那么可以使用 類名.方法名直接訪問該類方法。
4.static 修飾代碼塊
static 修飾的代碼塊被稱為靜態(tài)代碼塊,在JVM第一次記載該類時執(zhí)行。因此,靜態(tài)代碼代碼塊只能執(zhí)行一次,通常用于一些系統(tǒng)設(shè)置場景。
package cn.lyxq.test04;public class ChinesePeople {private String name;private int age;//使用static修飾的成員變量稱為類變量,不會隨著成員變化而變化,屬于所有成員共享private static String country ;//static修飾的代碼塊稱為靜態(tài)代碼塊,在JVM第一次加載該類的時候執(zhí)行,只能執(zhí)行一次static{country = "中國";System.out.println("country屬性已經(jīng)被賦值");}public ChinesePeople(String name,int age){this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}//類方法public static String getCountry() {return country;}//類方法public static void setCountry(String country) {ChinesePeople.country = country;}
}
package cn.lyxq.test04.test;import cn.lyxq.test04.ChinesePeople;public class ChinesePeopleTest {public static void main(String[] args) {ChinesePeople cp = new ChinesePeople("張三",20);}}