Java Polymorphism How to call to super class method for subclass object

我的未来我决定 提交于 2019-11-27 02:45:22

问题


Here is an example of what I am trying to ask

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

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

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.

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.


回答1:


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 
}



回答2:


There are many ways to do it. One way: don't override Names#initials() in ThreeNames.

Another way is to add a method to ThreeNames which delegates to Names#initials().

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

    public String basicInitials() {
        return super.initials();
    }
}



回答3:


I would instead leave initials alone in the superclass and introduce a new method that will return the complete initials. So in your code I would simply rename the initials method in ThreeNames to something else. This way your initials method is the same across the implementations of Name



来源:https://stackoverflow.com/questions/14907424/java-polymorphism-how-to-call-to-super-class-method-for-subclass-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!