创建对象的Java调用类

创建对象的Java调用类,java,Java,我想知道如何选择、操作创建对象的类 代码: public myclass(){ public anotherclass a = new anotherclass(); } 另一类: //how to use the class that created this class ? 基本上,你不能。如果您的另一个类需要知道实例或创建它的类,则应该通过构造函数传递该信息。例如: public class Parent { private final C

我想知道如何选择、操作创建对象的类

代码:

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;
    }
}

(这使父实例可供子实例使用-如果您只对该类感兴趣,您可以传递
parent.class
,而
child
构造函数将使用
class parentClass
参数。

您可以创建一个将
myclass
作为参数的构造函数:

public class Myclass
{
    Anotherclass a;

    public Myclass()
    {
         a = new Anotherclass(this);
    }
}

class Anotherclass
{
    private Myclass m;

    public Anotherclass(Myclass m)
    {
       this.m = m;
    }
}
通过

将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
的参数传递给另一个class对象:

public anotherclass{

    private myclass object;

    Public anotherclass(myclass object){

        this.object = object;

    }
}
将对象称为:

public myclass(){

       public anotherclass a = new anotherclass(this);    

}

你能澄清你的问题吗?你想在另一个类中编辑myClass()对象吗?