【Java】多态

来源:互联网 发布:centos7端口聚合 编辑:程序博客网 时间:2024/06/05 23:49

定义:子类对象可以直接赋值给父类对象,但运行时依然表现子类的行为特征,同一个类型的对象在执行同一个方法时,表现出多种行为特征。

向下转型:子类 子类对象=(子类)父类实例

调用子类的自定义方法instanceof 返回布尔类型 

向上转型(upcasting):父类 父类对象=子类对象

public class Test extends BaseClass {public String book="轻量级Java";public void test(){    System.out.println("子类覆盖父类的方法");}public void sub(){    System.out.println("子类普通方法");}public static void main(String[] args){    BaseClass bc=new BaseClass();    System.out.println(bc.book);    bc.test();    bc.base();    Test t=new Test();    System.out.println(t.book);    t.test();    t.base();    }}

//子类对象可以直接赋值给父类对象
BaseClass sc=new Test();
System.out.println(sc.book);
//sc只能调用BaseClass类(编译时)的方法
//不能调用Test(运行时)的方法
sc.base();
sc.test();

Student是Person的子类Person p = new Student();//向上转型Student s = (Student)p;//向下转型

子类强转父类

(父类)子类对象.方法名|变量名

错误异常: ClassCastException
instanceof

引用类型变量+instanceof+类(接口)
前一个对象是否是后面的类

//先用instanceof判断一个对象是否可以强制转换   Public Boolean checkInstance(Object obj){ If(obj instanceof Person){         }   }

复用:

class Animal{    private void beat(){    out.println("心胀跳动。。。");}    public void breath(){    beat();    out.println("吸一口,呼一口。。。");}}class Bird{    private Animal a;    public Bird(Animal a){    this.a=a;}    public void breath(){    a.breath();}    public void fly(){    out.println("空中飞行。。。");}}class Wolf{    private Animal a;    public Wolf(Animal a){        this.a=a;}    public void breath(){        a.breath();}    public void run(){        out.println("跑。。。");}}public class Test1 {    public static void main(String[] args)    {        Animal a1=new Animal();        Animal a2=new Animal();        Bird bird=new Bird(a1);        bird.breath();        bird.fly();        Wolf wolf=new Wolf(a1);        wolf.run();        wolf.breath();    }}

继承:Person→Teacher
组合:Person→Arm

0 0
原创粉丝点击