2013-05-22 57 views
24

我的任務是製作一個帶有實例變量的程序,一個字符串,應該由用戶輸入。但我甚至不知道實例變量是什麼。什麼是實例變量?我如何創建一個?它有什麼作用?Java - 什麼是實例變量?

+2

http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html – Maroun

回答

52

實例變量是一個類的內部聲明的變量,但在方法外:是這樣的:

class IronMan{ 

    /** These are all instance variables **/ 
    public String realName; 
    public String[] superPowers; 
    public int age; 

    /** Getters/setters here **/ 
} 

現在這個鐵人三項類可以在其他類中實例化以使用這些變量,如:

class Avengers{ 
     public static void main(String[] a){ 
       IronMan ironman = new IronMan(); 
       ironman.realName = "Tony Stark"; 
       // or 
       ironman.setAge(30); 
     } 

} 

這就是我們如何使用實例變量。更多有趣的東西在Java基礎知識here

19

一個實例變量是一個變量,它是一個類的實例的成員(即與創建一個與new創建的東西相關聯),而類變量是類本身的成員。

類的每個實例都有其自己的實例變量副本,而每個靜態(或類)變量只有一個與該類本身相關聯。

difference-between-a-class-variable-and-an-instance-variable

這個測試類說明差異

public class Test { 

    public static String classVariable="I am associated with the class"; 
    public String instanceVariable="I am associated with the instance"; 

    public void setText(String string){ 
     this.instanceVariable=string; 
    } 

    public static void setClassText(String string){ 
     classVariable=string; 
    } 

    public static void main(String[] args) { 
     Test test1=new Test(); 
     Test test2=new Test(); 

     //change test1's instance variable 
     test1.setText("Changed"); 
     System.out.println(test1.instanceVariable); //prints "Changed" 
     //test2 is unaffected 
     System.out.println(test2.instanceVariable);//prints "I am associated with the instance" 

     //change class variable (associated with the class itself) 
     Test.setClassText("Changed class text"); 
     System.out.println(Test.classVariable);//prints "Changed class text" 

     //can access static fields through an instance, but there still is only 1 
     //(not best practice to access static variables through instance) 
     System.out.println(test1.classVariable);//prints "Changed class text" 
     System.out.println(test2.classVariable);//prints "Changed class text" 
    } 
} 
+0

正確。你也可以將一個實例變量想象成一個對象中的「field」。一個相關的概念是封裝(見:private訪問修飾符,getter和setter ...) – vikingsteve

+0

事實上,我已經公開大多數公共事物以方便訪問,這通常是一個壞主意 –

相關問題