Have a look at this example:
class Parent{
Child child = new Child();
Random r = new Random();
}
class Child{
public Child(){
//access a me
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.