【发布时间】:2016-04-28 18:05:22
【问题描述】:
我有以下课程:
abstract class Parent
{
private ClassDependentOnSize classDependentOnSize;
public Parent ()
{
this.classDependentOnSize = new ClassDependentOnSize(size());
}
public abstract int size ();
}
class Child extends Parent
{
private String DBSelection;
private String[] DBSelectionArgs;
public Child (String selection, String... selectionArgs)
{
super();
this.DBSelection = selection;
this.DBSelectionArgs = selectionArgs;
}
@Override
public int size()
{
//FAILS because Parent calls size before DBSelectionArgs is initialized
String temp = "";
for(String str : DBSelectionArgs)
temp += str;
return temp.length;
//This function basically does a calculation that should not be
//done before hand. I have posted the exact method below.
}
}
class ClassDependentOnSize
{
public ClassDependentOnSize(int size)
{
}
}
虽然这不是我的 exact 类,但这是同样的问题。我写了这个来删除所有不必要的代码。
如你所见,超类试图在子类完成初始化之前调用size()来构造依赖于size的类。我很好奇过去有人如何解决这个问题。我相信每个人都知道, super() 必须是子构造函数的第一行。正如我已经列出了这些课程,这是一个糟糕的设计吗?感觉这个问题应该是以前发生过的,但是找不到解决办法。
编辑: 这是确切的方法。它用于 Android 应用程序。
protected Cursor getCursor()
{
if (songCursor == null)
{
songCursor = GET_SONGS_CURSOR(getContext(), MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString(), selection, selectionArgs, selection);
if (!songCursor.moveToFirst())
Standard.Loge("|NewPlaylist.getCursor| Could not move to first.");
}
int count = songCursor.getCount();
songCursor.close();
return count;
}
【问题讨论】:
-
@khelwood 我认为你的意思是可覆盖,而不是重载
-
@ControlAltDel 非常正确。
标签: java inheritance constructor abstract