如何在 Java 中访问对象的父对象? [英] How to access an object's parent object in Java?
本文介绍了如何在 Java 中访问对象的父对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
看看这个例子:
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()
}
}
如何从 Child 对象中访问 Random 对象?
How can I access the Random object from within the Child object?
推荐答案
让 Parent
类将自己的 Random
实例传递给 Child
> 班级.
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){
}
}
经典的奥卡姆剃刀.
这篇关于如何在 Java 中访问对象的父对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文