Java Polymorphism How to call a superclass method on a subclass object

Here is an example of what I'm 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 subclass - 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 a Threename object using ThreeNames example1 = new ThreeNames("Bobby", "Sue" "Smith") , then call System.out.println(example1.initials()); I will get BSS , I will get it.

My question is how to call the initials method, which is in the Name class, so my output is BS

+7
source share
3 answers

not. after you redefine a method, any external call to this method will be redirected to your overridden method (except, of course, if you redefine it even further along the inheritance chain). you can call the super method only from your own overridden method:

 public String someMethod() { String superResult = super.someMethod(); // go on from here } 

but this is not what you are looking for here. you could turn your method into:

 public List<String> getNameAbbreviations() { //return a list with a single element } 

and then in the subclass do the following:

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

There are many ways to do this. One way: do not override Names#initials() in ThreeNames .

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

 public class ThreeNames extends Name { // snip... public String basicInitials() { return super.initials(); } } 
+5
source

Instead, I would leave the initials in the superclass only and implement a new method that will return the full initials. So in your code, I would simply rename the initials method in ThreeNames to another. So your initials method is the same in all implementations of Name

+1
source

All Articles