【问题标题】:Change a static variable defined in superclass before making call from subclass constructor在从子类构造函数调用之前更改超类中定义的静态变量
【发布时间】:2020-01-13 12:52:33
【问题描述】:

我有 classA 和静态 PooledConnectionFactory 变量。 classB 扩展 A.

public class A{
    private static PooledConnectionFactory con;
    public A(){
        this("gets URL from defaults properties file");
    }
    public A(final String url){
       if(con==null){
         //Initialize pooled connection       
       }
//code for connection here
    }
}
public class B extends A {

    private PooledConnectionFactory conn;

    public B(String url){
        super(url);

    }


    public B(){
        super();
    }

}

我想将PooledConnectionFactory 作为一个非静态变量,以便为每项服务选择单独初始化。由于它是扩展 A,因此调用转到 A 的构造函数。

为了实现这一点,我应该在 B 类中进行哪些更改?

【问题讨论】:

  • 只需删除static?我看不出有什么问题。
  • 你的问题很不清楚。你想让con 非静态吗?是什么阻止你这样做?你到底想达到什么目标?
  • 我正在对现有产品进行更改,以确保新更改不会影响原始流程我在不同类别中进行更改
  • 两个con 对象应该相同吗?在这种情况下,从B protected 中创建一个并从A 中删除conn
  • @qomzwinx 是的,但是您到底想实现什么?您是否希望 B 的不同实例使用不同的工厂,即使在超类方法中也是如此?如果不更改 A,这是不可能的。

标签: java inheritance constructor


【解决方案1】:

使用单例而不是 A 构造函数

public class A {

    private static PooledConnectionFactory con;

    public A() {
        this("gets URL from defaults properties file");
    }

    public A(final String url) { }

    public static PooledConnectionFactory getPooledConnectionFactory() {
        if (con == null) {
            //Initialize pooled connection
        }
        return con;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    相关资源
    最近更新 更多