2014-12-30 17 views
0

爲什麼這樣做時,IDE說你需要改變str1str2static爲什麼可以在main中創建非靜態變量,但不在main之外。 Java的

public class Test { 

    String str1; 
    String str2; 

    public static void main(String[] args){ 


     str1 = "A"; 
     str2 = "B"; 
    } 
} 

但是,這是罰款:

public class Test { 



     public static void main(String[] args){ 

      String str1; 
      String str2; 
      str1 = "A"; 
      str2 = "B"; 
     } 
    } 

爲什麼確定申報非靜態變量在一個靜態方法裏面,但在靜態方法外面不行嗎?

+6

局部變量既不是靜態的也不是非靜態的。它們與類/實例變量不同。 –

+1

你的第二個例子使用局部變量,而不是靜態的。你會想看一個教程來學習局部變量,實例變量和靜態變量之間的區別。 –

+0

第一個示例:不能以'static'方式訪問'instance'變量(反之亦然)。 –

回答

1

類中的靜態方法只引用類的靜態成員。 「main」方法與普通靜態方法相同,遵循相同的規則。

對於類的非靜態成員,您必須首先初始化類的實例,然後才能訪問該成員。

public class Test { 

    String str1; 
    String str2; 

    public String getStr1(){ 
     return str1; 
    } 

    public String setStr1(){ 
     this.str1 = str1; 
    } 

    public static void main(String[] args){ 
     //create an instance of the class firstly. 
     Test test = new Test(); 

     // read and write the str1 
     System.out.println(test.getStr1()); 
     test.setStr1("A") 
     System.out.println(test.getStr1()); 
    } 
} 
0
public class Test { 

    String str1; //This is a variable that will be specific to each instance of the class Test 
    String str2; //This is a variable that will be specific to each instance of the class Test 

    public static void main(String[] args){ 


     str1 = "A"; //This static method is not dependent on any instance 
        //so as far as a static method is concerned there is not str1 
     str2 = "B"; //This static method is not dependent on any instance 
        //so as far as a static method is concerned there is not str3 
    } 
} 

public class Test { 



     public static void main(String[] args){ 

      String str1; //This variable is now independent of any instances of Test 
      String str2; //This variable is now independent of any instances of Test 
      str1 = "A"; //You can access those static variables from outside an instance 
      str2 = "B"; //You can access those static variables from outside an instance 
     } 
    } 
相關問題