【发布时间】:2022-06-10 16:54:47
【问题描述】:
在这里学习Java,我尝试对一个超类进行强制转换,但我无法访问子类方法,这可能吗,我做错了什么。
我有这个:
public class Musician {
public String name;
public String surname;
}
public class Instrumentist extends Musician{
public String getInstrumento() {
return instrumento;
}
public void setInstrumento(String instrumento) {
this.instrumento = instrumento;
}
private String instrumento;
public Instrumentist(String nombre, String name, String surname){
this.name = nombre;
this.surname = surname;
}
}
public class Main {
public static void main(String[] args) {
Musician m = new Instrumentist("Antonio", "Vivaldi", "none");
System.out.println(m);
}
}
我知道我可以做 Instrumentist i = new Instrumentist("Antonio", "Vivaldi", "none") 但是,Cast to superclass 的目的是什么?
【问题讨论】:
-
不,你没有做错任何事。不,你不能从超类访问子类方法,除非你强制转换,这就是它的工作原理。关于目的,我建议找到一些关于核心 OOP 概念的指南 - 抽象、多态、继承、封装。
-
我上周刚参加了考试,现在我有空,正在阅读“Head First Java (Kathy Sierra, Bert Bates)”所以我有这种“愚蠢”的问题,现在还不清楚我。我知道多态性,但在我的观点中可以理解这种特殊情况。谢谢回答:)
标签: java casting initialization subclass superclass