2017-05-17 7 views
0
public class Jail { 

    private int x=4; 

    public static void main(String[] args) { 

     int x=6; 
     new Jail().new Cell().slam(); 
    } 


    class Cell 
    { 
     void slam() 
     { 
      System.out.println("throw away key "+x); 

     } 
    } 
} 

このプログラムを実行すると、インスタンス変数xの値が出力されます。私はローカル変数xの値にアクセスしたい。どうやってするか?ローカル変数対インスタンス変数?

+3

あなたが印刷しようとしている範囲にないので、できません。それは "ローカル"であることの全体的な点です – Stultuske

答えて

1

ローカル変数として、そのようにアクセスすることはできません。 パラメータとしてメソッドに渡す必要があります。

public class Jail { 
    private int x=4; 

    public static void main(String[] args) { 
     stub int x=6; 
     new Jail().new Cell().slam(x); 
    } 

    class Cell { 
     void slam(int x) { 
      System.out.println("throw away key "+x); 
     } 
    } 

} 
+0

Excelent @adi、それはそれを行うための本当に良い方法です、それは完全に大丈夫です、私はポーが何をしようとしているのか少し混乱していますが、私に :)。すばらしいです –

0

あなたはこれを試してみることができます。

public class Jail { 
    private int x=4; 

    public static void main(String[] args) { 
     int x=6; 
     new Jail().new Cell().slam(x); 
    } 
    class Cell 
    { 
     void slam(int x) 
     { 
      System.out.println("throw away key "+x); 
     } 
    } 
} 

これはあなたのローカル変数を与える必要があります。ありがとうございました

0

私はあなたが抽象化を行いたいと思って、委任を加え、ゲッターとセッターを追加したいと思っています。もしあなたがすべてを組み合わせるなら、このようなsomithingをすることができます。何らかの理由であなたがしたくない場合は、最後に行うことができます:

public class Jail { 

    private int x = 4; 

    public Jail(int x) { 
     this.x = x; 
    } 

    public int getValue() { 
     return this.x; 
    } 

    static class Cell { 

     private Jail j; 

     public Cell(Jail j) { 
      this.j = j; 
     } 

     void slam() { 
      System.out.println("throw away key " + this.getValue()); 
     } 

     public int getValue() { 
      return this.j.getValue(); 
     } 
    } 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     int x = 6; 
     Jail j = new Jail(x); 
     Cell c = new Cell(j); 
     c.slam(); 
    } 
} 
関連する問題