向上转型:程序自动完成
格式:父类 父类对象=子类实例
向下转型:强制类型转换
格式:子类 子类对象=(子类)父类实例
class A{
public void tell1() {
System.out.println("A");
}
public void tell2() {
System.out.println("B");
}
}
class B extends A{
public void tell1() {
System.out.println("C");
}
public void tell3() {
System.out.println("D");
}
}
public class Test01 {
public static void main(String[] args) {
//向上转型
B b= new B();
A a=b;
a.tell1();
a.tell2();
//向下:必须先发生向上转型,再发生向下转型
A a=new B();
B b=(B)a;
b.tell1();
b.tell2();
b.tell3();
}
多态性案例:
class A1{
public void tell1() {
System.out.println("A-tell1");
}
}
class B1 extends A1{
public void tell2() {
System.out.println("B-tell2");
}
}
class C1 extends A1{
public void tell3() {
System.out.println("C-tell3");
}
}
class D1 extends A1{
}
public class Test02 {
public static void main(String[] args) {
say(new B1());
say(new C1());
say(new D1());
}
public static void say(A1 a) {//直接A1 A传参,调用tell1方法
a.tell1();
}
判断对象是否为类的实例
public static void main(String[] args) {
A2 x=new A2();
System.out.println(x instanceof A2);
System.out.println(x instanceof B2);
A2 y =new B2();
System.out.println(y instanceof A2);
System.out.println(y instanceof B2);
}
结果:
true
false
true
true

被折叠的 条评论
为什么被折叠?



