java中downcast向下轉型到底有什麽用? 舉例說明!
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();錯誤
/*
我們不能去掉下面的話,因為SuperClassM_t_w沒有printA方法。馬 克-to-wi n:we can not comment
the following statement,because SuperClassM_t_w does not have the method
of printA, report error */
SubClass sc = (SubClass) s1;
。。。。。。。。。。。。。。。。。。。
詳情請見:http://www.mark-to-win.com/index.html?content=JavaBeginner/javaUrl.html&chapter=JavaBeginner/JavaBeginner3_web.html#PointDowncast
java中downcast向下轉型到底有什麽用? 舉例說明!