局部变量与实例变量?

时间:2017-05-17 16:58:52

标签: java instance-variables local-variables

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 个答案:

答案 0 :(得分:0)

作为一个局部变量,你无法像这样访问它。您需要将其作为参数传递给您的方法。

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

}

答案 1 :(得分: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);
        }
    }
}

这应该给你本地变量。感谢

答案 2 :(得分:0)

我认为你想要进行抽象,然后委托,再加上getter和setter,如果你把所有这些结合起来,你可以像这样做,但我强烈建议将你的Cell类分成另一个.java类,但如果由于某种原因你不想,你最终可以做到:

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();
    } 
}