基类指针指向派生类,我们已经很熟了。(视频下载) (全部书籍)假如我们想用派生类反过来指向基类,就需要有两个要求: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
原文地址:https://www.cnblogs.com/mark-to-win/p/9693479.html