将其在Java的超级阶级施放

发布于 2025-02-06 02:35:07 字数 776 浏览 3 评论 0原文

在这里学习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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

青衫负雪 2025-02-13 02:35:09

这个概念是这样的:
超类/接口提供一般实施或合同。子类覆盖/实施合同。
为了确保您可以在运行时分配该合同的不同实现,您可以使用超类的引用并分配子类的对象。
音乐家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 in Musician class, but if your subclass has any other methods apart from those defined superclass, you can not access them using 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文