Java Polymorphism如何为子类对象调用超类方法
这是我想要问的一个例子
超类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; }
然后子类是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; }
所以如果我用ThreeNames example1 = new ThreeNames("Bobby", "Sue" "Smith")
创建一个Threename对象ThreeNames example1 = new ThreeNames("Bobby", "Sue" "Smith")
然后调用System.out.println(example1.initials());
我会得到BSS
我得到的。
我的问题是有没有办法调用Name类中的initials方法,以便我的输出只是BS
没有。 一旦你重写了一个方法,那么从外部对该方法的任何调用都将被路由到被覆盖的方法(当然,如果它再次在inheritance链中进一步被覆盖)。 你只能从你自己的重写方法中调用super方法,如下所示:
public String someMethod() { String superResult = super.someMethod(); // go on from here }
但这不是你在这里寻找的东西。 你可以把你的方法变成:
public List getNameAbbreviations() { //return a list with a single element }
然后在子类中执行此操作:
public List getNameAbbreviations() { List fromSuper = super.getNameAbbreviations(); //add the 3 letter variant and return the list }
有很多方法可以做到这一点。 一种方法:不要覆盖ThreeNames
Names#initials()
。
另一种方法是向ThreeNames
添加一个方法,该方法委托给Names#initials()
。
public class ThreeNames extends Name { // snip... public String basicInitials() { return super.initials(); } }
我宁愿将首字母留在超类中,并引入一个将返回完整首字母的新方法。 因此,在您的代码中,我只需将ThreeNames中的initials方法重命名为其他内容。 这样,您的首字母缩写方法在Name的实现中是相同的