gpt4 book ai didi

java - 创建一个在类之间共享其属性的对象

转载 作者:行者123 更新时间:2023-12-01 13:10:24 25 4
gpt4 key购买 nike

我想创建一个A类的对象,并在B类、C类和D类中初始化它

该对象应该被共享;也就是说,如果对这些类(C 和 D)中的 objA 进行任何更改,即使在 objC、'objD' 被销毁之后,其内容仍然保持不变,假设 B 类 是主类。我想使用它的属性是class B

class A {}

class B
{
initialize class A object and use-change its property
initialize class C object and use-change its property
initialize class D object and use-change its property
}

class C{initialize class A object and use-change its property}

class D{initialize class A object and use-change its property}

class X{initialize B and destroy objC,objD, from objB use property of objA of class B}

最佳答案

非静态尝试如下所示:

您的目标对象:

public class A {

}

您的类,对对象执行某些操作:

public class C {
private final A a;

public C(final A a) {
this.a = a;
}

public foo() {
// do something with a
}
}

public class D {
private final A a;

public D(final A a) {
this.a = a;
}

public otherFoo() {
// do something with a
}
}

您的主类(class):

public class B {

public static void main(String[] args) {
final A a = new A();

final C c = new C(a);
final D d = new D(a);


c.foo();
d.otherFoo();
}
}

关于java - 创建一个在类之间共享其属性的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22916284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com