【问题标题】:Using method of one class from another class using 'this' keyword in constructor在构造函数中使用“this”关键字从另一个类中使用一个类的方法
【发布时间】:2014-12-10 04:25:51
【问题描述】:

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

    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();
        }
    }

我期待输出:“方法 1:100”。但是,我得到了输出:“OUTER.java:16: error: non-static method Get_Value() cannot be referenced from a static context value=Get_Value();”。我怎样才能使它工作?

干杯!

拉杰什。

【问题讨论】:

  • 您能说出您面临的问题吗?我尝试了相同的程序,它成功了。
  • 这对我有用,你的问题是什么?
  • 对不起各位,我已经更新了程序来呈现真正的问题。感谢您的回复!
  • 帖子标题谈到“在构造函数中使用this”,但示例中没有一个构造函数,也没有this...

标签: java nested-class


【解决方案1】:

一种方法是在 NESTED2 中有一个 NESTED1 的实例。例如:

private static class NESTED2
  {
    private NESTED1 nested1;
    public NESTED2 (NESTED1 nested1) {
        this.nested1 = nested1;
    }
    public void Method2()
    {
      nested1.Method1();
    }
  }

【讨论】:

  • 感谢克里斯的快速回复!
【解决方案2】:
private static class NESTED2
{
  public void Method2(NESTED1 nested1Instance)
  {
   nested1Instance.Method1();
  }
}

这应该与您的班级结构有关。相反,通过这样的修改......

private static class NESTED1
{
  public *statc* void Method1()
  {
    ...
  }
}
private static class NESTED2
{
  public *static* void Method2()
  {
    NESTED1.Method1();
  }
}

...你可以不创建对象而侥幸。

如果将方法设为静态,则无需实例化(创建)类对象即可首先调用它们。

【讨论】:

  • 感谢 Eli 的回复!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-22
  • 2020-11-07
  • 2014-03-12
  • 1970-01-01
  • 2021-07-09
  • 1970-01-01
相关资源
最近更新 更多