1. 程式人生 > >何使用派生類指針指向基類,即downcast向下轉型?

何使用派生類指針指向基類,即downcast向下轉型?

xpl lan ini who efault out sta bsp anim

基類指針指向派生類,我們已經很熟了。(視頻下載) (全部書籍)假如我們想用派生類反過來指向基類,就需要有兩個要求:1)馬克-to-win:基類指針開始時指向派生類,2)我們還需要清清楚楚的轉型一下。

if you want to use derived class pointer
point to base class, there are two requirements:
1) base class pointer is initially the type of the derived class like Animal a2 = new Dog();
2) 馬克-to-win:we still need to explicitly cast it like Dog d = (Dog)a2;

What is the point of downcast? (視頻下載) (全部書籍)當一個方法只有子類才有,馬克-to-win:不是說基類和子類都有,開始時又是基類指針指向派生類,這時就需要downcast, see the following example. after you cast with SubClass,sc is pure SubClass type.

例1.9.1---本章源碼 

class SuperClassM_t_w {
int a;
SuperClassM_t_w() {
a = 5;
}
public void printAsuper() {
System.out.println("父類中a =" + a);
}
}

class SubClass extends SuperClassM_t_w {
int a;
SubClass(int a) {
this.a = a;
}
public void printA() {
System.out.println("子類中a = " + a);
}
}
public class Test {
public static void main(String args[]) {
/* note that new SubClass(10) will call SuperClassM_t_w(), default constructor. */
SuperClassM_t_w s1 = new SubClass(10);
s1.printAsuper();//基類指針指向派生類時,馬克-to-win: 可以用基類指針調用基類僅有的方法, 但不能調用子類僅有的方法。必須向下強轉一下。
// s1.printA();錯誤

。。。。。。。。。。
詳情請見:http://www.mark-to-win.com/index.html?content=JavaBeginner/javaUrl.html&chapter=JavaBeginner/JavaBeginner3_web.html#HowToUseDowncasting

何使用派生類指針指向基類,即downcast向下轉型?