java - 在构造函数中使用 'this' 关键字使用另一个类的一个类的方法

标签 java nested-class

我在一个类中有两个嵌套类,外部类扩展另一个类。结构是这样的。

    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/

相关文章:

c# - 对常量使用嵌套类?

c# - 嵌套类和动态调用问题

c++ - 在嵌套类中对 operator[] 的调用不明确

java - Android 查看音频文件 NumberFormatException

java - Jackson objectMapper,尝试将 LocalDate 序列化为 "yyyy-MM-dd",将 LocalTime 序列化为 "HH:mm:ss"

java - Java 中不太像 Unix 的终端滚动

c# - 为什么一个类不能在 C# 中扩展它自己的嵌套类?

java - 使用 ENUM 作为配置文件,但需要一个字符串

java - 使用两个 try-catch?

.net - 在 NHibernate 中映射嵌套类的 XML 语法是什么