简体   繁体   中英

I have an object of an outer class. How do I get the object of the inner class from it?

public class Class1 {

  public Class2 getClass2() {
  //How can I implement this method?
  }

  public class Class2 {
  //...
  }
}

I just can't get it done, even though it should only be one line of code...

You should not do this. The inner class should be used in the outer class and not elsewhere. If you need an instance of the inner class then it should be not an inner class.

Just create a getter method in the outer class like this.

public class Class1 {

  public Class2 getClass2() {
  //How can I implement this method?
  }

  public Class2 getClass2() {
    return new Class2();
  }

  public class Class2 {
  //...
  }
}

I think you are getting the concept of inner classes wrong. In your example, you have a public inner class. That doesn't mean that your Class1 has exactly one object of Class2 . You can still create as many objects of Class2 as you like. If you want to do this outside of Class1 use new Class1.Class2() . While this is possible, it would be bad design as galovics correctly mentioned in his answer.

If what you are trying to achieve is having one object reference to a Class2 object inside Class1 , use a field of type Class2 in Class1 and a matching getter method:

public class Class1 {

    private Class2 class2instance = new Class2();

    public Class2 getClass2() {
        return class2instance;
    }

    private class Class2 {
        //...
    }
}
public class Class1 {
    private Class2 class2 = new Class2();

    public Class2 getClass2() {
        return class2;
    }

    public class Class2 {
    //...
    }
}

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