Java多态如何调用子类对象的超类方法 [英] Java Polymorphism How to call to super class method for subclass object

查看:23
本文介绍了Java多态如何调用子类对象的超类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想问的一个例子

超类名称.java

public class Name{
  protected String first;
  protected String last;

      public Name(String firstName, String lastName){
         this.first = firstName;
         this.last = lastName;
      }

       public String initials(){
         String theInitials = 
            first.substring(0, 1) + ". " +
            last.substring(0, 1) + ".";
         return theInitials;
      } 

然后子类是 ThreeNames.java

and then the subclass is ThreeNames.java

public class ThreeNames extends Name{
  private String middle;

   public ThreeNames(String aFirst, String aMiddle, String aLast){
     super(aFirst, aLast);
     this.middle = aMiddle;
  }

   public String initials(){
     String theInitials = 
        super.first.substring(0, 1) + ". " +
        middle.substring(0, 1) + ". " +
        super.last.substring(0, 1) + ".";
     return theInitials;
  }

因此,如果我使用 ThreeNames example1 = new ThreeNames("Bobby", "Sue" "Smith") 创建一个 Threename 对象,然后调用 System.out.println(example1.initials)()); 我会得到 BSS 我明白了.

so if i create an Threename object with ThreeNames example1 = new ThreeNames("Bobby", "Sue" "Smith") and then call System.out.println(example1.initials()); I will get B.S.S. I get that.

我的问题是有没有办法调用 Name 类中的 initials 方法,以便我的输出只是 B.S.

My question is is there a way to call the initials method that is in the Name class so that my output is just B.S.

推荐答案

没有.一旦您覆盖了一个方法,那么从外部对该方法的任何调用都将被路由到您的覆盖方法(当然,如果它在继承链的下游再次被覆盖).您只能像这样从自己的重写方法内部调用 super 方法:

no. once you've overridden a method then any invocation of that method from outside will be routed to your overridden method (except of course if its overridden again further down the inheritance chain). you can only call the super method from inside your own overridden method like so:

public String someMethod() {
   String superResult = super.someMethod(); 
   // go on from here
}

但这不是你在这里寻找的.你可以把你的方法变成:

but thats not what youre looking for here. you could maybe turn your method into:

public List<String> getNameAbbreviations() {
   //return a list with a single element 
}

然后在子类中这样做:

public List<String> getNameAbbreviations() {
   List fromSuper = super.getNameAbbreviations();
   //add the 3 letter variant and return the list 
}

这篇关于Java多态如何调用子类对象的超类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆