如何在类范围外但在父类范围内访问变量?(How can I access variables outside class scope but inside parent class scope? [d

编程入门 行业动态 更新时间:2024-10-23 01:56:20
如何在类范围外但在父类范围内访问变量?(How can I access variables outside class scope but inside parent class scope? [duplicate])

这个问题在这里已有答案:

访问内部类 2中的 外部类变量

我有一个考试示例,询问我是否可以访问包含值1的x变量? 我可以解决这个问题,但我对此究竟是什么感兴趣?

class A { int x = 1; //this is what I need access to. class B { int x = 2; void func(int x) {...} } }

This question already has an answer here:

Accessing outer class variable in inner class 2 answers

I have an exam example which ask whether or not can I access the x variable containing the value 1? The solution is that I can, but I'm interested how exactly?

class A { int x = 1; //this is what I need access to. class B { int x = 2; void func(int x) {...} } }

最满意答案

class A { int x = 1; class B { int x = 2; void func(int x) { System.out.println(A.this.x); } } }

使用示例:

public class Main { public static void main(String[] args) { A a = new A(); A.B b = a.new B(); b.func(0); // Out is 1 } } class A { int x = 1; class B { int x = 2; void func(int x) { System.out.println(A.this.x); } } }

Using example:

public class Main { public static void main(String[] args) { A a = new A(); A.B b = a.new B(); b.func(0); // Out is 1 } }

更多推荐

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

发布评论

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

>www.elefans.com

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