繁体   English   中英

在构造函数中使用“ this”关键字使用另一类的方法

[英]Using method of one class from another class using 'this' keyword in constructor

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

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

...您可以不创建任何对象而逃脱。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM