首页 > 解决方案 > 构造函数重载 - Java 中的最佳实践

问题描述

构造函数也可以像任何其他方法一样重载,我知道这一事实。由于一项任务,我决定使用具有多个构造函数的抽象超类:

抽象超类:

protected ListSortierer()
{
  this( null, null );
}

protected ListSortierer( List<E> li )
{
  this( li, null );
}

protected ListSortierer( Comparator<E> comp )
{
  this( null, comp );     
}

protected ListSortierer( List<E> li, Comparator<E> com )
{
  this.original = Optional.ofNullable( li );
  this.comp = Optional.ofNullable( com );
}

要访问这些构造函数中的每一个,我还需要子类中的多个构造函数。

BubbleSort.java:

public ListBubbleSort()
{
  super();
}

public ListBubbleSort( List<E> li )
{
  super( li );
}

public ListBubbleSort( Comparator<E> com )
{
  super( com );
}

public ListBubbleSort( List<E> li, Comparator<E> com )
{
  super( li, com );
}

在这种情况下,子类的每个构造函数都会立即调用超类的构造函数。我想到我可以再次引用自己的构造函数并传递null值:

public ListBubbleSort()
{
  this( null, null );
}

public ListBubbleSort( List<E> li )
{
   this( li, null );
}

public ListBubbleSort( Comparator<E> com )
{
   this( null, com );
}

public ListBubbleSort( List<E> li, Comparator<E> com )
{
   super( li, com );
}

这样做可以让我省略抽象超类中的 3 个重载构造函数,但会强制每个子类都遵循相同的模式。

我的问题是:在一致性的情况下,更好的方法是什么?处理抽象超类或子类中的缺失值?它对实例化有影响还是只是一个意见问题?

标签: javainheritanceconstructorinstancesuperclass

解决方案


在一致性的情况下,有什么更好的方法?

  1. 将所有子构造函数设为私有。
  2. 引入静态工厂方法。

    ListBubbleSort.withList(List<E> list)
    ListBubbleSort.withComparator(Comparator<E> comparator)
    
  3. 调用适当的super构造函数。不要通过任何nulls。

    public static <E> ListBubbleSort withList(List<E> list) {
        return new ListBubbleSort(list);
    }
    
    private ListBubbleSort(List<E>) {
        super(list);
    }
    
    protected ListSortierer(List<E>) {
        // initialise only the list field
        this.origin = list;
    }
    
  4. 不要Optional用作字段。

    this.original = Optional.ofNullable(li);

  5. 如果您有 3 个以上的参数,请考虑构建器模式。

处理抽象超类或子类中的缺失值?

构造函数应该提供初始值。您没有传递初始值,您只是表示它们的缺席

默认情况下,null是引用类型的初始值。因此,如果尚未给出字段的值,则无需重新分配字段。

它对实例化有影响还是只是一个意见问题?

可读性、维护性。


我建议阅读Joshua Bloch 的 Effective Java

创建和销毁对象

  • 第 1 项:考虑静态工厂方法而不是构造函数
  • 第 2 项:在面对许多构造函数参数时考虑使用构建器

推荐阅读