我在一个类中有两个嵌套类,外部类扩展另一个类。结构是这样的。
public class EXTENSION_CLASS
{
public int Get_Value()
{
return(100);
}
}
public class OUTER extends EXTENSION_CLASS
{
public static class NESTED1
{
public void Method1()
{
int value=0;
value=Get_Value();
System.out.println("Method1: "+value);
}
}
public static class NESTED2
{
NESTED1 Nested1_Instance=new NESTED1();
public void Method2()
{
Nested1_Instance.Method1();
}
}
public void run()
{
NESTED2 Nested2_Instance=new NESTED2();
Nested2_Instance.Method2();
}
public static void main (String[] args)
{
OUTER New_Class=new OUTER();
New_Class.run();
}
}
我期待输出:“Method1:100”。但是,我得到输出:“OUTER.java:16:错误:无法从静态上下文 value=Get_Value() 引用非静态方法 Get_Value();”。我怎样才能让它工作?
干杯!
拉杰什。
最佳答案
一种方法是在 NESTED2 中拥有 NESTED1 的实例。例如:
private static class NESTED2
{
private NESTED1 nested1;
public NESTED2 (NESTED1 nested1) {
this.nested1 = nested1;
}
public void Method2()
{
nested1.Method1();
}
}
关于java - 在构造函数中使用 'this' 关键字使用另一个类的一个类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27393344/