如何在Java中访问对象的父对象?

And*_*ann 0 java oop

看看这个例子:

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()
    }
}
Run Code Online (Sandbox Code Playgroud)

如何从Child对象中访问Random对象?

dca*_*tro 7

Parent类将自己的实例传递RandomChild类.

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

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

class Child{    
    public Child(Random r){

    }    
}
Run Code Online (Sandbox Code Playgroud)

经典奥卡姆剃刀.