gpt4 book ai didi

Java多态性如何为子类对象调用父类(super class)方法

转载 作者:搜寻专家 更新时间:2023-10-30 21:20:01 24 4
gpt4 key购买 nike

这是我想问的一个例子

父类(super class) 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 对象,然后调用 System.out.println(example1.initials ()); 我会得到 B.S.S. 我明白了。

我的问题是有没有一种方法可以调用 Name 类中的 initials 方法,以便我的输出只是 B.S.

最佳答案

没有。一旦你覆盖了一个方法,那么从外部对该方法的任何调用都将被路由到你覆盖的方法(当然,除非它在继承链的下方再次被覆盖)。你只能从你自己重写的方法中调用 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
}

关于Java多态性如何为子类对象调用父类(super class)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14907424/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com