這裏是什麼,我想問問的Java多態性如何調用父類方法的子類對象
超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;
}
所以,如果我創建一個Threename物體ThreeNames example1 = new ThreeNames("Bobby", "Sue" "Smith")
,然後調用System.out.println(example1.initials());
我會得到B.S.S.
我明白了。
我的問題是有沒有辦法來調用的縮寫方法是在名稱類,使我的輸出就是B.S.
非常感謝您的答案! – 2013-02-16 06:00:34
[使用子類對象訪問超類函數](http://stackoverflow.com/questions/2432249/accessing-super-class-function-using-subclass-object) – 2015-01-20 23:16:27