[英]Java Polymorphism How to call to super class method for subclass object
这是我要问的一个例子
超类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
没有。 一旦您重写了一个方法,那么从外部对该方法的任何调用都将被路由到您的重写的方法(当然,除非它在继承链的更下方再次被重写)。 您只能从自己的重写方法内部调用super方法,如下所示:
public String someMethod() {
String superResult = super.someMethod();
// go on from here
}
但这不是您在这里想要的。 您可以将您的方法转换为:
public List<String> getNameAbbreviations() {
//return a list with a single element
}
然后在子类中执行以下操作:
public List<String> 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方法重命名为其他名称。 这样,您的Initials方法在Name的实现中是相同的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.