在java中使用static時需要注意哪些問題?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
1、使用static方法的時候,只能訪問static聲明的屬性和方法,而非static聲明的屬性和方法是不能訪問的。
package com.jk.ref; class People{ String name; private static String country="中國"; public People(String name){ this.name=name; } public void tell(){ System.out.println("name:"+name+" "+"country:"+country); } /** * @return the country */ public static String getCountry() { return country; } /** * @param country the country to set */ public static void setCountry(String country) { People.country = country; } } public class StaticDemo01 { public static void main(String[] args) { // TODO Auto-generated method stub People.setCountry("shanghai"); People ps1=new People("zhangsan"); //People.country="上海"; ps1.tell(); People ps2=new People("lisi"); // ps2.country="上海"; ps2.tell(); People ps3=new People("wangwu"); // ps3.country="上海"; ps3.tell(); } }
2、父類引用只能調父類和子類重寫方法,父子同名方法不會覆蓋而是遮蔽。
public class TestMain { public static void main(String[] args) { Super sup = new Sub(); //封裝(向上造型) sup.m1(); //父類引用無法調子類未重寫方法,輸出mi in Super sup.m2();//調用子類方法m2,繼承先構建父類方法,方法名相同覆蓋(重寫)方法,輸出m2 in Sub Sub sub = (Sub)sup; //拆箱(向下造型) sub.m1(); //調用子類靜態方法m1,先構建父類方法,方法名相同方法名相同遮蔽方法,輸出m2 in Sub sub.m2();//調用子類方法m2,繼承先構建父類方法,方法名相同覆蓋(重寫)方法,輸出m2 in Sub } } class Super{ //父類 public static void m1() { //父類靜態方法 System.out.println(“m1 in Super”); } public void m2() { //父類方法 System.out.println(“m2 in Super”); } } class Sub extends Super{ //子類 public static void m1() { //子類靜態方法 System.out.println(“m1 in Sub”); } public void m2() { //子類方法 System.out.println(“m2 in Sub”); } }
內容擴展:
深度總結
引用一位網友的話,說的非常好,如果別人問你static的作用;如果你說靜態修飾 類的屬性 和 類的方法 別人認為你是合格的;如果是說 可以構成 靜態代碼塊,那別人認為你還可以; 如果你說可以構成 靜態內部類, 那別人認為你不錯;如果你說了靜態導包,那別人認為你很OK;
那我們就先在這幾方面一一對static進行總結;然后說一些模糊的地方,以及一些面試中容易問道的地方;
static方法
static方法一般稱作靜態方法,由于靜態方法不依賴于任何對象就可以進行訪問,因此對于靜態方法來說,是沒有this的,因為它不依附于任何對象,既然都沒有對象,就談不上this了。并且由于這個特性,在靜態方法中不能訪問類的非靜態成員變量和非靜態成員方法,因為非靜態成員方法/變量都是必須依賴具體的對象才能夠被調用。
看完上述內容,你們掌握在java中使用static時需要注意哪些問題的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。