简体   繁体   English

在 Java 中将对象强制转换为其超类

[英]Cast an Object to its superclass in Java

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.在这里学习Java,我尝试对一个超类进行强制转换,但我无法访问子类方法,这可能吗,我做错了什么。

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?我知道我可以做 Instrumentist i = new Instrumentist("Antonio", "Vivaldi", "none") 但是 Cast to superclass 的目的是什么?

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 in Musician class, but if your subclass has any other methods apart from those defined superclass, you can not access them using m .在这里,使用m ,您可以调用Musician类中定义的方法,但如果您的子类除了定义的超类之外还有其他方法,则无法使用m访问它们。
If subclass overrides any method, then even after using reference of superclass, say m , java would make sure that at runtime , overridden method in subclass is called.如果子类覆盖了任何方法,那么即使在使用超类的引用之后,比如m ,java 也会确保在runtime调用子类中的覆盖方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM