Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 306
Kailua Bum Avatar asked Feb 16 '13 05:02

Kailua Bum


3 Answers

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 
}
like image 110
radai Avatar answered Nov 20 '22 15:11

radai


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();
    }
}
like image 42
Matt Ball Avatar answered Nov 20 '22 13:11

Matt Ball


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

like image 2
ZeusSelerim Avatar answered Nov 20 '22 13:11

ZeusSelerim