怎么样判断父类对象是不是子类对象

来源:百度知道 编辑:UC知道 时间:2024/06/02 03:18:10
import java.util.Arrays;
public class extends1{
public static void main(String[] args) {
AA ob=new AA(5,9,4);
((BB)ob).copy();
((BB)ob).copy1();
((BB)ob).show();

}
}
class AA{
int a[]=new int [5];
AA(){}
AA(int a,int b,int c){
this.a[0]=a;
this.a[1]=b;
this.a[2]=c;
}
}
class BB extends AA{
int b[]=new int[5];
BB(int a,int b,int c){
super(a,b,c);
}
public void copy(){
for (int i:a)
{System.out.print(i+"\t");}
}
public void copy1(){
this.b=Arrays.copyOf(super.a,super.a.length);
}
public void show(){
for (int i:a)
{System.out.print(i+"\t");}
System.out.println("");
for (int i:b)
{System.out.print(i+"\t");}
}
}
以上程序有点错误,重要问题是:怎么样判断父类对象是不是子类对象?可以进行强制转换!

给你举个例子
a b c 三个类
b 和c继承 a

b = new a()
c = new a();
你看能不能编译过去

a = new b()
a = new c();

a = new b();
((b)a)这样是可以的 因为a 的原类型是b

a = new b();
((c)a)是不可以的 因为a 的原类型是b

而你的例子 编译的时候应该是可以通过的
运行的时候就不对了
a = new a()
((b)a)转不出来的
这也就是拆箱 装箱的过程
装进去是什么类型拆出来就应该是什么