简体   繁体   中英

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

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 BSS 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 BS

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 
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM