62,615
社区成员
发帖
与我相关
我的任务
分享
Father father = (Father)new son();
呢?
class base {// a base class
// constructor
public base() {
System.out.println("base class construct");
}
// perform
public void perform() {
System.out.println("base class perform");
}
}
class subbase extends base {// derive from base
// constructor
public subbase() {
System.out.println("sub class construct");
}
// perform
public void perform() {
System.out.println("sub class perform");
}
}
public class casting {// test casting class
// constructor
public casting() {
System.out.println("begin casting test");
}
public static void main(String args[]) {
base father = new base();
subbase son = new subbase();
System.out.println("---------------------");
father = son; // <1> 你在这里把father指向了 son,也就son指向的new subbase();
//此时的 father和son 其实是相同的了。如果你把这句去掉,你在看看 <2>会不会爆掉。
father.perform();
son = (subbase)father; // <2>
son.perform();
father = (base) ((subbase) father); // <3>
father.perform();
System.out.println("------------------------");
((base)new subbase()).perform();
}
}
package test;
// codes start
class base {// a base class
// constructor
public base() {
System.out.println("base class construct");
}
// perform
public void perform() {
System.out.println("base class perform");
}
}
class subbase extends base {// derive from base
// constructor
public subbase() {
System.out.println("sub class construct");
}
// perform
public void perform() {
System.out.println("sub class perform");
}
}
public class casting {// test casting class
// constructor
public casting() {
System.out.println("begin casting test");
}
public static void main(String args[]) {
base father = new base();
subbase son = new subbase();
System.out.println("---------------------");
father = son; // <1>
father.perform();
son = (subbase)father; // <2>
son.perform();
father = (base) ((subbase) father); // <3>
father.perform();
System.out.println("------------------------");
((base)new subbase()).perform();
}
}