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

后端 未结 4 1414
既然无缘
既然无缘 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 01:57

    Have the Parent class pass its own instance of Random to the Child class.

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

    Classic Occam's razor.

提交回复
热议问题