java_多态

一、多态(对象的多种形态
1.引用的多态
父类的引用指向本类的对象
父类的引用指向子类的对象(引用多态)
(不允许子类对象指向父类)
2.方法多态
创建本类对象时调用的方法为本类的方法
创建子类对象时,调用的方法为子类重写的方法或继承的方法
**使用多态时,两个类一定要有继承关系
当子类拥有的方法父类没有时,指向子类的父类对象无法调用。

package com.sy;

public class Animal {
public void eat()
{
    System.out.println("动物有吃的能力");
}
}
package com.sy;

public class Dog extends Animal {
    public void eat()
    {
        System.out.println("狗屎吃肉的");
    }
    public void watchdoor()
    {
        System.out.println("狗具有看门的能力");
    }
}
package com.sy;

public class initail {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        /*Animal pro1=new Animal();
        Animal pro2=new Dog();
        Animal pro3=new Cat();
        pro1.eat();
        pro2.eat();
        pro3.eat();*/
        
        Dog dog=new Dog();
        Animal animal=dog;//自动类型转换提升,向上类型转换
        if(animal instanceof Dog)
        {
            Dog dog2=(Dog)animal;//向下类型转换
        }
        else{
            System.out.println("无法进行类型转换 转换成dog类型");
        }
        
        /*判断一个引用是否是某个类型或某个类型的子类型会返回一个bool值*/
        if(animal instanceof Cat)
        {
            Cat cat =(Cat)animal;//编译时为Cat类,运行时实际开辟的内存是Dog类型的,运行时会报错
        }
        else{
            System.out.println("无法进行类型转换  转换成cat类型");
        }
    }
}
package com.sy;

public class Cat extends Animal {

}

练习(描述运输工具)
汽车:在陆地上(陆地载客40人)
轮船:在海上(海上200人)
飞机:在天上(天空XXX人)
运输客人,各自的运输方式
创建五个以上生活当中的和交通工具,并同时查看他们的运输客人的方式


引用类型的转换
1.向上类型的转换(隐式/自动类型转换(子类强制转换成父类)),是小类型到达类型的转换(无风险)
2.向下类型的转换(强制类型转换),大类型到小类型的转换(有风险,可能发生数据溢出)
3.可以使用instanceof运算符,来解决引用对象的类型,避免类型转换的安全性问题

4.用于验证是否可以进行强制类型转换

if(animal instanceof Cat)
{
Cat cat =(Cat)animal;//编译时为Cat类,运行时实际开辟的内存是Dog类型的,运行时会报错
}

else{

System.out.println("无法进行类型转换 转换成cat类型");
}

 

package com.sy;
public class Trantool {
public void tran()
{
    System.out.println("运输方式");
}
}
package com.sy;
public class tramain {
    public static void main(String[] args) {
        Trantool tran1=new Trantool();
        Trantool tran2=new Car();
        Trantool tran3=new Board();
        Trantool tran4=new Plant();        
        tran1.tran();
        tran2.tran();
        tran3.tran();
        tran4.tran();
    }

}
package com.sy;
public class Car extends Trantool {
    public void tran()
    {
        System.out.println("小汽车的运输方式");
    }
}



package com.sy;
public class Plant extends Trantool {
    public void tran()
    {
        System.out.println("飞机的运输方式");
    }
}
原文地址:https://www.cnblogs.com/excellencesy/p/7818305.html