动态创建实例名称?

时间:2015-02-15 20:10:35

标签: java

考虑以下哪些不起作用。应该怎么做才能使它发挥作用。我想动态创建歌曲的实例,s1,s2,s3等。我意识到歌曲中没有对象的方法,但是我也不能将s1,s2,s3分配给歌曲。

int i;
String s;

for(i=0; i < 4; i++)
{
    //Stuff to get song info omitted. 

    Object thisSong = s + Integer.toString(i);//append 1 to s

    thisSong = new Song(title, artist, playTime, fileName);//create new object 

    System.out.println(thisSong.getTitle());// Error here.  getTitle() is undefined. 
}   

//下面的歌曲课......

public class Song
{
private String title;
private String artist;
private int playTime; // in seconds
private String fileName;

public Song(String title, String artist, int playTime, String fileName)
{
    this.title = title;
    this.artist = artist;
    this.playTime = playTime;
    this.fileName = fileName;
}

public String getTitle()
{
    return title;
}

public String getArtist()
{
    return artist;
}

public int getPlayTime()
{
    return playTime;
}

public String getFileName()
{
    return fileName;
}

@Override
public String toString()
{
    return  String.format("%-20s %-20s %-25s %10s",title, artist, fileName, playTime);
}

}

2 个答案:

答案 0 :(得分:1)

我不确定你想要实现的目标。其他答案建议转换,但如果您尝试执行ClassCastException,则会获得Song song = (Song)thisSong;,因为您在thisSong中存储的内容不是Song对象,而是{ {1}}。

因为您正试图致电String我相信您想要为您的歌曲生成标题。所以也许尝试这样的事情:

getTitle

答案 1 :(得分:0)

变量 thisSong 具有对象类型,但对象类型没有getTitle()方法。 所有你需要的只是将 thisSong 投射到Song类型:

Song song = (Song)thisSong;
song.getTitle();

((Song)thisSong).getTitle();