How do I access the parent object of an object in Java?

advertisements

Have a look at this example:

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

class Child{

    public Child(){
        //access a method from Random r from here without creating a new Random()
    }
}

How can I access the Random object from within the Child object?


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.