static 關鍵字詳解 static方法調用非static屬性和方法


  靜態的屬性和方法在內存中的存放地址與非靜態的是不同的,靜態的是存放在static區,它意味着靜態方法是沒有this的,所以我們不可以從一個static方法內部發出對非static方法的調用。但是反之是可以的。

  靜態屬性被外部公用,修改之后會被保存。

1、static方法沒有this,我們通過類名來調用static屬性和方法

 1 package demo;
 2 
 3 public class TestStatic {
 4     private static int i = 18;  //靜態屬性被外部公用,修改之后會被保存。
 5     private String str = "###";  //靜態方法不能調用非靜態的屬性和方法
 6     static void run(){
 7         //TestStatic.i  不在同一個類中通過類名類調用static屬性
 8         i = i * 100;
 9         System.out.println("劉二狗在跑了" + i +"步");
10     }
11     
12     static void print(){
13         run();
14         //TestStatic.run();   不在同一個類中通過類名類調用static方法
15         System.out.println("測試static:i = " + i);
16     }
17     
18     public static void main(String[] args) {
19         TestStatic.print();
20     }
21 }

打印結果:

 

2、static方法調用非static屬性和方法。我們把一個對象的句柄放到static方法內部,通過這個對象的句柄就可以調用非static的屬性和方法。代碼如下:

package demo;
/**
 * static方法調用非static屬性和方法
 * @author dyf
 *
 */
public class TestStatic {
    private static int i = 18;
    private String str = "###";
    static TestStatic ts = new TestStatic();
    
    TestStatic test(){
        this.str = str + "===";
        System.out.println(str);
        return this;
    }
    
    static void run(TestStatic ts){
        ts.str = ts.str + "$$$"; //通過句柄調用非static的屬性
        ts.test();   //通過句柄調用非static的方法
        System.out.println("劉二狗在跑步!" + ts.str);
    }
    
    public static void main(String[] args) {
        TestStatic.run(ts);
    }
}

打印結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM