/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
int x,y,sum;
public static void main (String[] args) throws java.lang.Exception
{
//Create outer object
Ideone ideOne = new Ideone();
//instantiate inner object, and call method
Ideone.InnerClass ic = ideOne.new InnerClass();
ic.printSum(5,4);
}
private class InnerClass {
private void printSum(int x,int y) {
//reference the outer object instance
Ideone.this.x=x;
Ideone.this.y=y;
Ideone.this.sum = x + y;
System.out.println(Ideone.this.sum);
}
}
}
public class ShadowTest {
public int x = 0;
class FirstLevel {
public int x = 1;
void methodInFirstLevel(int x) {
System.out.println("x = " + x);
System.out.println("this.x = " + this.x);
System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
}
}
public static void main(String... args) {
ShadowTest st = new ShadowTest();
ShadowTest.FirstLevel fl = st.new FirstLevel();
fl.methodInFirstLevel(23);
}
}
4条答案
按热度按时间tjvv9vkg1#
你可以试试这个:
4jb9z9bj2#
如果要执行此操作,首先需要示例化外部类,然后示例化内部类,如下所示:
已经在这里进行了测试:http://ideone.com/e.js/drizsg
vcirk6k63#
使用
OuterClass.this.x
;OuterClass.this
引用父对象(从中InnerClass
对象已生成)。请考虑以下oracle官方教程中发布的黯然失色的示例:
与输出
w8ntj3qf4#
另一种方法是使外部类成员受到保护