为什么这段代码不起作用?
public class BB { private class A { private int x; } public static void main(String[] args) { A a = new A(); a.x = 100; System.out.println(a.x); } }虽然这段代码有用吗?
public class BB { private class A { private int x; } static int y = 3; public static void main(String[] args) { BB b = new BB(); b.compile(); System.out.println("y = "+ y); } public void compile() { A a = new A(); a.x = 100; System.out.println(a.x); System.out.println("y = "+ y); } }在第一个代码中,当我试图通过内部类'a'的对象引用内部类'A'的实例变量'x'时,我收到一个错误,说我在静态上下文中使用内部类。 在其他方法中执行相同操作时没有错误。
Why isn't this code working
public class BB { private class A { private int x; } public static void main(String[] args) { A a = new A(); a.x = 100; System.out.println(a.x); } }while this code is working?
public class BB { private class A { private int x; } static int y = 3; public static void main(String[] args) { BB b = new BB(); b.compile(); System.out.println("y = "+ y); } public void compile() { A a = new A(); a.x = 100; System.out.println(a.x); System.out.println("y = "+ y); } }In first code, When I am trying to refer to instance variable 'x' of inner class 'A' by an object of inner class 'a', I am getting an error saying that I'm using inner class in static context. There is no error while doing the same in some other method.
最满意答案
您的错误与字段访问无关。 此行的编译失败:
A a = new A();原因:您无法在没有封闭实例的情况下实例化内部类,这正是该行代码尝试执行的操作。 你可以改写
A a = (new BB()).new A();这将提供内联的封闭实例。 然后您也可以访问私有字段。
或者,只需使A类static ,这意味着它没有封闭的实例。
Your error has nothing to do with field access. Compilation fails for this line:
A a = new A();Reason: you cannot instantiate an inner class without an enclosing instance, which is exactly what that line of code tries to do. You could write instead
A a = (new BB()).new A();which would provide an enclosing instance inline. Then you will be able to access the private field as well.
Alternatively, just make the A class static, which means it does not have an enclosing instance.
更多推荐
发布评论