How to access an object's parent object in Java?

后端 未结 4 1415
既然无缘
既然无缘 2021-01-29 01:36

Have a look at this example:

class Parent{
    Child child = new Child();
    Random r = new Random();
}

class Child{

    public Child(){
        //access a me         


        
4条回答
  •  不要未来只要你来
    2021-01-29 02:00

    It may be the case that if only your Parent class ever creates instances of Child, for its own internal use, then you could use inner classes, like so:

    class Parent {
        Random r = new Random();
        Child child = new Child();
    
        private class Child {
            Child() {
                Parent.this.r; // Parent's instance of Random
            }
        }
    }
    

    There are other reasons why you may want to use inner classes. But, I'm hesitant to suggest them, because requiring access to another class's instance variables is generally not a good practise.

提交回复
热议问题