简体   繁体   中英

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

I have two nested classes inside a class with the outer class extending another class. The structure is something like this.

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

I'm expecting the output: "Method1: 100". But, am getting the output: "OUTER.java:16: error: non-static method Get_Value() cannot be referenced from a static context value=Get_Value();". How can i make this working?

Cheers !

Rajesh.

One approach would be to have an instance of NESTED1 in NESTED2. For example:

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

That should do it with your class structure. Instead, with a modification like so....

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

... you could get away with no creation of objects.

If you make the methods static, you don't need to instantiate(create) a class object to call them first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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