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

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

问题描述

以下是我想要问的一个例子

Here is an example of what I am trying to ask

超类名字.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创建Threename对象=新的ThreeNames(Bobby,SueSmith)然后调用 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方法,以便我的输出只是 BS

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 
}

然后在子类中执行此操作:

and then in the subclass do this:

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

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

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