【问题标题】:Cast an Object to its superclass in Java在 Java 中将对象强制转换为其超类
【发布时间】: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


【解决方案1】:

这个概念是这样的:
超类/接口提供通用实现或契约。子类覆盖/实现该合同。
为了确保您可以在运行时分配该合同的不同实现,您可以使用超类的引用并将子类的对象分配给它。
Musician m = new Instrumentist("Antonio", "Vivaldi", "none");
在这里,使用m,您可以调用在Musician 类中定义的方法,但是如果您的子类除了定义的超类之外还有任何其他方法,则无法使用m 访问它们。
如果子类重写了任何方法,那么即使在使用了超类的引用之后,比如m,java 也会确保在runtime,调用子类中的重写方法。

【讨论】:

    猜你喜欢
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-26
    相关资源
    最近更新 更多