gpt4 book ai didi

在父构造函数中初始化子对象之前,Java 抽象父对象调用子方法

转载 作者:行者123 更新时间:2023-11-29 04:46:28 25 4
gpt4 key购买 nike

我有以下类(class):

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)
{

}
}

虽然这不是我的确切 类,但这是同样的问题。我写这个是为了删除所有不必要的代码。

如你所见,父类(super class)试图在子类完成初始化之前调用size()来构造依赖于size的类。我很好奇过去有人如何解决这个问题。我相信每个人都知道,super() 必须是子构造函数中的第一行。正如我已经列出的这些类(class),这是一个糟糕的设计吗?我觉得这一定是以前发生过的问题,但我找不到解决方案。

编辑:这是确切的方法。它用于 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;
}

最佳答案

我以前确实遇到过这个问题。重要的教训是你永远不应该在 Parent 构造函数中调用非私有(private)方法,这样就不会发生这种情况

关于在父构造函数中初始化子对象之前,Java 抽象父对象调用子方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36922315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com