问题描述
- java类的强制转换问题
-
package lesson4;
class A
{
public void func1()
{
System.out.println("A func1 is calling");
}
public void func2()
{
func1();
}
}
class B extends A
{
public void
func1()
{
System.out.println("B func1 is calling");
}
public void func3()
{
System.out.println("B func3 is calling");
}
}
class C
{
public static void main(String [] args)
{
B b = new B();
callA(b);
A a = b;
callA(new A());
}
public static void callA(A a)
{
B b = (B)a;
b.func1();
b.func2();
b.func3();
}
}
以上为代码部分
B func1 is calling
B func1 is calling
B func3 is calling
Exception in thread "main" java.lang.ClassCastException: lesson4.A cannot be cast to lesson4.B
at lesson4.C.callA(A.java:36)
at lesson4.C.main(A.java:32)以上为运行结果出错部分
望各位大神抽出时间予以解答
解决方案
java 强制类项转换
20111220 关于java强制转换
Java 强制类型转换(类转换注意事项)
解决方案二:
callA(new A());这里的实例是A,B是继承A的,是A的子类,父类实例不能转成子类实例,反过来可以
解决方案三:
public class TestExtend {
public static void main(String[] args) {
B b = new B();
callA(b);
A a = b;//b 能被强转 因为b是子类
callA(new A());//但你传入一个父类,父类在下面的方法中就不能被转成子类了。
}
public static void callA(A a){
B b = (B)a;
b.func1();
b.func2();
b.func3();
}
}
class A{
public void func1(){
System.out.println("A func1 is calling");
}
public void func2(){
func1();
}
}
class B extends A{
public void func1(){
System.out.println("B func1 is calling");
}
public void func3(){
System.out.println("B func3 is calling");
}
}
时间: 2024-09-21 00:10:20