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

  靜態的屬性和方法在內存中的存放地址與非靜態的是不一樣的,靜態的是存放在static區,它意味着靜態方法是沒有this的,因此咱們不能夠從一個static方法內部發出對非static方法的調用。可是反之是能夠的。測試

  靜態屬性被外部公用,修改以後會被保存。this

一、static方法沒有this,咱們經過類名來調用static屬性和方法spa

 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 }

打印結果:code

 

二、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);
    }
}

打印結果:blog

相關文章
相關標籤/搜索