L.S*_*ner 17 java inheritance constructor instance superclass
构造函数也可以像任何其他方法一样重载,我知道这个事实.由于任务,我决定使用具有多个构造函数的抽象超类:
摘要超类:
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 );
}
Run Code Online (Sandbox Code Playgroud)
要访问每个构造函数,我还需要子类中的多个构造函数.
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 );
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,子类的每个构造函数都会立即调用超类的构造函数.我想到我可以再次引用自己的构造函数并传递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 );
}
Run Code Online (Sandbox Code Playgroud)
这样做将允许我省略抽象超类中的3个重载构造函数,但会强制每个子类遵循相同的模式.
我的问题是:在一致性的情况下,更好的方法是什么?处理抽象超类或子类中的缺失值?它是否会对实例化产生影响,还是只是意见问题?
And*_*lko 14
在一致性的情况下,更好的方法是什么?
介绍静态工厂方法.
ListBubbleSort.withList(List<E> list)
ListBubbleSort.withComparator(Comparator<E> comparator)
Run Code Online (Sandbox Code Playgroud)调用适当的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;
}
Run Code Online (Sandbox Code Playgroud)this.original = Optional.ofNullable(li);
如果您有3个以上的参数,请考虑使用Builder模式.
处理抽象超类或子类中的缺失值?
构造函数应该提供初始值.你没有传递初始值,你只是表明他们的缺席.
默认情况下,null是引用类型的初始值.因此,如果没有给出它的值,则不需要重新分配字段.
它是否会对实例化产生影响,还是只是意见问题?
可读性,维护.
我建议阅读Joshua Bloch撰写的Effective Java:
创建和销毁对象
| 归档时间: |
|
| 查看次数: |
1669 次 |
| 最近记录: |