gpt4 book ai didi

java - 抽象类及其子类

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:07:54 25 4
gpt4 key购买 nike

我有以下代码是我在网上找到的,这可能是一个简单的问题,但你的解释对我有很大帮助。

这是名为 SongComponent 的抽象类

public abstract class SongComponent {

public void add(SongComponent newSongComponent){

throw new UnsupportedOperationException();

}
public void remove(SongComponent newSongComponent){

throw new UnsupportedOperationException();

}

public SongComponent getComponent(int componentIndex){

throw new UnsupportedOperationException();

}

public String getSongName(){

throw new UnsupportedOperationException();

}

public String getBandName(){

throw new UnsupportedOperationException();

}

public int getReleaseYear(){

throw new UnsupportedOperationException();

}

public void displaySongInfo(){

throw new UnsupportedOperationException();

}




}

这是扩展名为 SongGroup 的抽象类的类

import java.util.ArrayList;
import java.util.Iterator;
public class SongGroup extends SongComponent {

ArrayList songComponents = new ArrayList();

String groupName;
String groupDescription;

public SongGroup(String newGroupName, String newGroupDesc){

groupName = newGroupName;
groupDescription = newGroupDesc;


}

public String getGroupName(){
return groupName;
}

public String getGroupDescription(){
return groupDescription;
}

// It overrides the add() method from its superclass
public void add(SongComponent newSongComp){
songComponents.add(newSongComp);
}

public void remove(SongComponent newSongComp){
songComponents.remove(newSongComp);
}

public SongComponent getComponent(int compIndex){
return (SongComponent)songComponents.get(compIndex);
}

public void displaySongInfo(){

System.out.println( getGroupName() + " " +
getGroupDescription());

Iterator songIterator = songComponents.iterator();

while(songIterator.hasNext()){
SongComponent songInfo = (SongComponent)songIterator.next();
songInfo.displaySongInfo();
}
}


}

我的问题是,在什么情况下,add()方法和其他被抽象类重写的方法会被调用?比如抽象类的add()方法会抛出new UnsupportedOperationException异常,什么时候调用?

最佳答案

SongComponent可能有其他不覆盖 SongGroup 的具体子类(add() 除外) .对于此类子类,调用 add()将执行基类实现并抛出 UnsupportedOperationException异常。

SongComponent 的另一种实现方式将是使当前抛出的所有方法 UnsupportedOperationException抽象,这将强制 SongComponent 的任何具体子类覆盖它们。

关于java - 抽象类及其子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34218936/

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