无法在Java中获取内部类变量的正确值

时间:2014-06-30 16:45:27

标签: java

我正在尝试访问内部类变量但无法实现它。

public int foo {

public int valueofX() {
    abc a = new foo().new abc();
    return a.getX(); 
}
private final class abc {
    private int x =0; // this value is changed later in the code

        public int getX() {
         return x; //this always give me 0
        }   
   }
}

3 个答案:

答案 0 :(得分:0)

你已经将foo声明为int - 这不应该是你的外类吗?

public class foo {

public static void main(String[] args) {
    foo f = new foo();
    int x = f.valueofX();
}
public int valueofX() {
    abc a = new abc();
    return a.getX();
}

private final class abc {
    private int x = 1; 

    public int getX() {
        return x; 
    }
}

}

x在这里是1 ......

你真的想在每次调用valueOfX()时创建一个新的abc() - 你可能希望abc成为foo的一个字段:

public class foo {

    private abc a = new abc();

    public static void main(String[] args) {
        foo f = new foo();
        int x = f.valueofX();
    }
    public int valueofX() {

        return a.getX();
    }

    private final class abc {
        private int x = 1;

        public int getX() {
            return x; 
        }
    }

}

答案 1 :(得分:0)

这是你的代码:

public int foo { 

public int valueofX() {
    abc a = new abc(); //You create a new 'abc' element and store it in 'a'
    return a.getX(); /*Here you access the method 'getX()' from 'a', and 'a' 
                       contains and 'abc' object. It gives you back the value x,
                       and it's with this method you could modify x.
                     */
}

    private final class abc {
        private int x = 0; // this value is changed later in the code

            public int getX() {
                 return x; //this always give me 0
            }              /*CORRECTION: This will give you 'X', that initially 
                             has the value of 0 */
    }

}

访问' x'变量' a' (abc class),你必须得到使用返回它的merthod。


如果您只想访问' x'价值,你做我写的。

a.valueOfX(); //This will return X, you can store it, operate with it, use it.

答案 2 :(得分:0)

我想你想要这个实现

 public class OuterClass {
    public int valueofX() {
        abc a = new OuterClass().new abc();
        a.setX(1);
        return a.getX();
    }
    private final class abc {
        private int x =0; // this value is changed later in the code

        public int getX() {
            return x; //this always give me 0
        }
        public void setX(int x)
        {
            this.x = x;
        }
    }
    public static void main(String arr[])
    {
        OuterClass x = new OuterClass();
        System.out.println(x.valueofX());
    }
    }