从外部类访问内部类的私有实例变量(Accessing private instance variable of inner class from outer class)

编程入门 行业动态 更新时间:2024-10-28 19:20:16
从外部类访问内部类的私有实例变量(Accessing private instance variable of inner class from outer class)

为什么这段代码不起作用?

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.

更多推荐

本文发布于:2023-08-04 12:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1415889.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:部类   变量   实例   Accessing   private

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!