马克社区吧 关注:483贴子:445
  • 0回复贴,共1

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();错误。。。。。。。。。。。。。。。。。。。
详情请见:http://www.mark-to-win.com/JavaBeginner/JavaBeginner3_web.html#PointDowncast