我对此代码有疑问:
public class Musician {
private String name;
public String instrument;
public Musician(String name, String instrument){
this.name= name;
this.instrument= instrument;
}
public String getInstrument() {
return instrument;
}
public String getName() {
return name;
}
private String getClassName(){
return "Musician ";
}
public void play(){
System.out.println("[M] "+getClassName() + " plays music.");
}
public void printInfo(){
play();
System.out.println("[M] Class name: "+ getClassName());
System.out.println("[M] Instrument: "+ getInstrument());
}
}
public class RockMusician extends Musician{
public String instrument;
public RockMusician(String name, String instrument) {
super(name, instrument);
this.instrument= instrument + " and drums";
}
public String getClassName(){
return " RockMusician ";
}
public void play(){
System.out.println("[RM] "+ getClassName() + getName() + " breaks his "+ super.getInstrument() + "!");
}
}
public class IsraelyRockMusician extends RockMusician {
public IsraelyRockMusician(String name, String instrument) {
super(name, instrument);
}
public String getInstrument() {
return instrument;
}
public String getName(){
return super.getName() + " the king";
}
public String getClassName() {
return " IsraelyRockMusician ";
}
}
public class Testing {
public static void func(Musician m){
System.out.println("I've got a musician!");
}
public static void func(RockMusician m){
System.out.println("I've got a rock musician!");
}
public static void main(String[] args) {
Musician m3 = new IsraelyRockMusician("Chanoch", "guitar");
m3.printInfo();
}
}
我有IsraelRockMusician继承了RockMusician,后者继承了音乐家,
然后,我制作一个音乐家m3,名称为“ chanoch”,乐器为“ guitar”
我激活该方法,打印信息,
因为printInfo在父级-> RockMusician中,它本身包含3个方法-> play(),getClassName()和getInstrument(),
我的问题是,当方法showinfo运行时,播放将一直进行到被覆盖的方法,并显示“ [RM] IsraelyRock音乐人Chanoch国王打破了吉他!”,
现在,这很好,但是下一行是“ [M]类名称:Musician”,这意味着将getClassName赋予“ Musician”,Im询问为什么自此方法被覆盖以来为什么没有“ IsraeliRockMusician”。
如果问题有点模糊,我感到抱歉。
最佳答案
问题在于基类的方法具有私有访问权限。
private String getClassName(){
return "Musician ";
}
将其更改为公共/受保护,以便您可以覆盖它。