将其在Java的超级阶级施放
在这里学习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);
}
}
我知道我可以做仪器i =新的仪器主义者(“ antonio”,“ vivaldi”,“ none”) 但是,铸造超级阶级的目的是什么?
Learning Java here and I try to cast on a super class and i cant access to subclass methods, is it possible, I am doing something wrong.
I have this:
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);
}
}
I know I can do Instrumentist i = new Instrumentist("Antonio", "Vivaldi", "none")
but then what is the purpose of Cast to superclass?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个概念是这样的:
超类/接口提供一般实施或合同。子类覆盖/实施合同。
为了确保您可以在运行时分配该合同的不同实现,您可以使用超类的引用并分配子类的对象。
音乐家M =新的仪器主义者(“ Antonio”,“ Vivaldi”,“ None”);
在这里,使用
M
,您可以调用Musicians
类中定义的方法,但是如果您的子类除了定义的超级类别外具有其他方法,您将无法访问它们使用M
。如果子类覆盖任何方法,那么即使使用超级类的引用,例如
m
,Java也会确保在Runtime
中,呼叫子类中的覆盖方法。The concept is like this:
The superclass/interface provides general implementation or a contract. The subclass overrides/implements that contract.
To make sure that you can assign different implementations of that contract at runtime, you use reference of a Superclass and assign object of a subclass to it.
Musician m = new Instrumentist("Antonio", "Vivaldi", "none");
Here, with
m
, you can call methods defined inMusician
class, but if your subclass has any other methods apart from those defined superclass, you can not access them usingm
.If subclass overrides any method, then even after using reference of superclass, say
m
, java would make sure that atruntime
, overridden method in subclass is called.