public class ClassA {
int i;
void display(){
System.out.print("this is A");
}
}
public class ClassB extends ClassA{
int j;
void display(){
System.out.print("this is B");
}
void show(){
}
}
public class Test { public static void main(String ...args){
// program1-------can't compile
// ClassA a = new ClassA();
// ClassB b = new ClassB();
// ClassA aRef;
// ClassB bRef;
// aRef = a;
// aRef.display();
// aRef =b;
// aRef.display();
// aRef.show();
// program2------can compile but throws an runtime exception
// ClassA a = new ClassA();
// ClassB b = new ClassB();
// ClassA aRef;
// ClassB bRef;
// aRef=a;
// bRef=(ClassB)aRef;
// bRef.show();
// program3-------can compile and run
ClassA a = new ClassA();
ClassB b = new ClassB();
ClassA aRef;
ClassB bRef;
aRef = a;
aRef.display();
aRef = b;
bRef =(ClassB)aRef;
bRef.show();
bRef.display();
}
}
这是我写的一个父类与子类之间转换的程序,请高手指点一下这三个程序结果产生的原因
int i;
void display(){
System.out.print("this is A");
}
}
public class ClassB extends ClassA{
int j;
void display(){
System.out.print("this is B");
}
void show(){
}
}
public class Test { public static void main(String ...args){
// program1-------can't compile
// ClassA a = new ClassA();
// ClassB b = new ClassB();
// ClassA aRef;
// ClassB bRef;
// aRef = a;
// aRef.display();
// aRef =b;
// aRef.display();
// aRef.show();
// program2------can compile but throws an runtime exception
// ClassA a = new ClassA();
// ClassB b = new ClassB();
// ClassA aRef;
// ClassB bRef;
// aRef=a;
// bRef=(ClassB)aRef;
// bRef.show();
// program3-------can compile and run
ClassA a = new ClassA();
ClassB b = new ClassB();
ClassA aRef;
ClassB bRef;
aRef = a;
aRef.display();
aRef = b;
bRef =(ClassB)aRef;
bRef.show();
bRef.display();
}
}
这是我写的一个父类与子类之间转换的程序,请高手指点一下这三个程序结果产生的原因
// program1-------can't compile
// ClassA a = new ClassA();
// ClassB b = new ClassB();
// ClassA aRef; //你最好要赋值防止空指针,ClassA aRef = null ;这是好习惯
// ClassB bRef; //同上
// aRef = a;
// aRef.display();
// aRef =b;
// aRef.display();
// aRef.show();
……
暂时说这些吧
// program1-------can't compile
// ClassA a = new ClassA();
// ClassB b = new ClassB();
// ClassA aRef; //你最好要赋值防止空指针,ClassA aRef = null ;这是好习惯
// ClassB bRef; //同上
// aRef = a;
// aRef.display();
// aRef =b; //这里是一个父类ClassA指向子类ClassB
// aRef.display();
// aRef.show(); //应该是这样会编译不通过,ClassB继承了ClassA,但是show方法是子类ClassB专有的,这里系统只把aRef当做ClassA来看待,系统看不到它的show方法,因为ClassB的show方法不是重写父类的方法。此时会报错。
继续分析到此,楼主自己验证看看,我电脑没jdk
//program2------can compile but throws an runtime exception
ClassA a = new ClassA();
ClassB b = new ClassB();
ClassA aRef;
ClassB bRef;
aRef=a;
bRef=(ClassB)aRef; //强制类型转换会发生异常
bRef.show();
进行这种强制类型转换,则aRef引用的实际类型,必须是ClassB类或是ClassB的子类,而aRef引用是ClassB父类类型
所以会产生ClassCastException