2013-05-22 4 views
24

私の割り当ては、ユーザーが入力する必要があるインスタンス変数、Stringを持つプログラムを作ることです。しかし、私はインスタンス変数が何であるか知りません。インスタンス変数とは何ですか?どのように作成するのですか?それは何をするためのものか?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で作成されたものに関連付けられている)変数ですが、クラス変数はクラス自体のメンバです。

クラスのすべてのインスタンスにはインスタンス変数のコピーがありますが、クラス自体に関連付けられた各静的(またはクラス)変数は1つのみです。

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

が正しい。また、インスタンス変数をオブジェクトの 'フィールド 'と考えることもできます。関連概念はカプセル化です( 'private'アクセス修飾子、ゲッターとセッターを参照してください)。 – vikingsteve

+0

実際には、ほとんどのものを簡単にアクセスできるように公開していますが、これは通常は悪い考えです –