如何在类范围外但在父类范围内访问变量?(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 answersI 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 } }更多推荐
发布评论