Java多态性如何调用子类对象的超类方法

Kailua流浪汉:

这是我要问的一个例子

超类Name.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

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;
  }

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

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

发现:

没有。一旦您重写了一个方法,那么从外部对该方法的任何调用都将被路由到您的被重写的方法(当然,除非它在继承链的下方再次被重写)。您只能从自己的重写方法内部调用super方法,如下所示:

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

但这不是您在这里想要的。您可以将您的方法转换为:

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 
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章