You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java同包下如何跨文件引用已创建的对象实例?

可行解决方案

下面是几种无需创建新实例,就能在IngresoUI中访问RegistroUI里CuentaBancaria实例的方法:

方法一:构造函数传递实例

  1. 在IngresoUI类中添加带参数的构造函数,保存传入的实例:
private CuentaBancaria cuenta;

public IngresoUI(CuentaBancaria cuenta) {
    this.cuenta = cuenta;
}
  1. 在RegistroUI中创建IngresoUI对象时,把已有的Cuenta实例传进去:
IngresoUI ingresoUI = new IngresoUI(Cuenta);
  1. 之后在IngresoUI里直接使用该实例:
textBienvenido.setText("BIENVENID@ USUARIO" + cuenta.getNombre());

方法二:静态字段共享(谨慎使用)

如果项目架构简单,可将实例设为静态字段:

  1. 在RegistroUI中修改实例定义为静态:
public static CuentaBancaria Cuenta = new CuentaBancaria(nombre);
  1. 在IngresoUI中通过类名直接访问:
textBienvenido.setText("BIENVENID@ USUARIO" + RegistroUI.Cuenta.getNombre());

注意:静态字段会长期驻留内存,若场景复杂可能引发状态混乱,仅适合单实例的简单场景。

方法三:单例模式改造CuentaBancaria类

修改CuentaBancaria类,确保全局只有一个实例:

  1. 改造CuentaBancaria类:
public class CuentaBancaria {
    private static CuentaBancaria instance;
    private String nombre;

    // 私有构造方法,禁止外部直接创建实例
    private CuentaBancaria(String nombre) {
        this.nombre = nombre;
    }

    // 带参数的实例获取方法,仅首次初始化时传入nombre
    public static CuentaBancaria getInstance(String nombre) {
        if (instance == null) {
            instance = new CuentaBancaria(nombre);
        }
        return instance;
    }

    // 无参获取实例方法,供后续场景使用
    public static CuentaBancaria getInstance() {
        return instance;
    }

    public String getNombre() {
        return nombre;
    }
}
  1. 在RegistroUI中初始化实例:
CuentaBancaria Cuenta = CuentaBancaria.getInstance(nombre);
  1. 在IngresoUI中获取实例并使用:
CuentaBancaria cuenta = CuentaBancaria.getInstance();
textBienvenido.setText("BIENVENID@ USUARIO" + cuenta.getNombre());

内容的提问来源于stack exchange,提问作者Valeria Lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 21:32:49