オブジェクトを作成したクラスを選択、操作する方法を知っているのだろうか。
コード :
public myclass(){
public anotherclass a = new anotherclass();
}
別のクラス:
//how to use the class that created this class ?
オブジェクトを作成したクラスを選択、操作する方法を知っているのだろうか。
コード :
public myclass(){
public anotherclass a = new anotherclass();
}
別のクラス:
//how to use the class that created this class ?
基本的に、できません。他のクラスがインスタンスまたはそれを作成したクラスのいずれかを知る必要がある場合は、コンストラクターを介してその情報を渡す必要があります。例えば:
public class Parent {
private final Child child;
public Parent() {
child = new Child(this);
}
}
public class Child {
private final Parent parent;
public Child(Parent parent) {
this.parent = parent;
}
}
(これにより、親インスタンスが子で使用できるようになります。 classのみに関心がある場合は、渡しParent.class
て、Child
コンストラクターでClass<?> parentClass
パラメーターを使用します。
構成によって
AnotherClass に MyClass インスタンスを配置し、そのコンストラクターを作成します。
class AnotherClass {
private MyClass myClass;
public AnotherClass(MyClass myClass) {
this.myClass = myClass;
}
public void domeSomethignWithMyClass() {
//myClass.get();
}
}
MyClass メソッドからの作成中に、インスタンスを渡します
public void someMyClassMethod() {
AnotherClass anotherClass = new AnotherClass(this);
//...
}
myclass
パラメータとして取得するコンストラクタを作成できます。
public class Myclass
{
Anotherclass a;
public Myclass()
{
a = new Anotherclass(this);
}
}
class Anotherclass
{
private Myclass m;
public Anotherclass(Myclass m)
{
this.m = m;
}
}
のパラメーターを -object に渡す必要がありmyclass
ますanotherclass
。
public anotherclass{
private myclass object;
Public anotherclass(myclass object){
this.object = object;
}
}
オブジェクトを次のように呼び出します。
public myclass(){
public anotherclass a = new anotherclass(this);
}