Java Polymorphism如何为子类对象调用超类方法

Kai*_*Bum 11 java methods polymorphism subclass

这是我想要问的一个例子

超类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;
      } 
Run Code Online (Sandbox Code Playgroud)

然后子类是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;
  }
Run Code Online (Sandbox Code Playgroud)

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

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

rad*_*dai 16

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

public String someMethod() {
   String superResult = super.someMethod(); 
   // go on from here
}
Run Code Online (Sandbox Code Playgroud)

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

public List<String> getNameAbbreviations() {
   //return a list with a single element 
}
Run Code Online (Sandbox Code Playgroud)

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

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


Mat*_*all 5

有很多方法可以做到这一点.方式一:不会覆盖Names#initials()ThreeNames.

另一种方法是添加ThreeNames委托给的方法Names#initials().

public class ThreeNames extends Name {
    // snip...

    public String basicInitials() {
        return super.initials();
    }
}
Run Code Online (Sandbox Code Playgroud)