简体   繁体   English

对对象的引用(通过 3 个类)

[英]Reference to object ( throught 3 classes)

I have a classes:我有一个课程:

class A{
// represents the fields
}

class B{
A objA = new A();
// assigning a values to an object (objA) of class A
}

class C{
//I need this object (objA) with assigned values in the class B to calculations in class C 
}

How to pass (references?) to the class C?如何将(引用?)传递给 C 类? Or if there is a better way to thank you in advance for your help.或者如果有更好的方式提前感谢您的帮助。 Singleton is not an option.单身不是一种选择。

I need to use object (objA) in class C.我需要在 C 类中使用对象 (objA)。

Expand your class B to something like:将您的B类扩展为:

public class B {
    private A objA = new A();

    public B() {
        objA.setA(4);
    }

    public A getObjA() {
        return objA;
    }
}

And class C should take a reference of A in its constructor like:C应该在其构造函数中引用A ,例如:

public class C {
    private A objA;

    public C(A objA) {
        this.objA = objA;
    }

    public A getObjA() {
        return objA;
    }
}

then in your main you can call:然后在你的主要你可以打电话:

public static void main(String[] args) {
    B bObj = new B();
    C cObj = new C(b.getObjA());

    System.out.println(cObj.getObjA().getA());
}

Now the object class C , cObj contains the same reference of class A object like the one in bObj现在对象类C , cObj包含与cObj中的对象相同的类A对象的bObj

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM