分类: Java
2006-06-29 12:23:39
1子类当父类用
//c4:B.java
//author:ZhangHongbin
//This program is protected by copyright laws.
//Upcasting of class.
class A
{
void func1(int i)
{
System.out.println(" func1="+i);
}
void func2( A a)
{
a.func1(1);
func1(2);
}
}
class B extends A
{
public static void main(String[] args)
{
B b=new B();
A a=new A();
b.func2(a);
System.out.println(" Begin upcasting");
b.func2(b); // Upcasting向上转换,子类可以当父类用
}
}
2 instance of的使用
//c4:X.java
//author:ZhangHongbin
//This program is protected by copyright laws.
//instanceof operator.
class A
{
}
class B extends A
{
}
class C extends B
{
}
public class X
{
public static void main(String[] args)
{
C obj=new C();
if (obj instanceof C)
System.out.println("obj is instanceof C.");
if (obj instanceof B)
System.out.println("obj is instanceof B.");
if (obj instanceof A)
System.out.println("obj is instanceof A.");
}
}
/**
当使用instance of X来检测obj是否为类A的对象时,要求obj所属的类和类X必须是子类和父类
的关系,即obj所在的类是类X,或则obj所在的类直接或间接继承了类X。
*/