多态和虚方法调用

1.多态定义:相同名字表示不同含义
(a)编译时多态:重载(参数不一样的同名)
(b)运行时多态:覆盖,子类对父类的覆盖
动态绑定———虚方法调用
2.上溯造型
派生类当作基本类处理
例:

Person p = new Student();

3.虚方法调用
实现运行时的多态,子类重载父类方法,根据实例类型选择方法调用
非final方法自动进行动态绑定。
例:

class mainTest
{
    static void fun(shape s) {s.draw();}
    public static void main(String[] args)
    {
        Circle c = new Circle;
        Triangle t = new Triangle();
        Line l = new Line();
        fun(c);
        fun(t);
        fun(l);
    }
}

class Shape
{
    void draw(){System.out.println("Shape Drawing"); }; 
}

class Cirlc extends Shape
{
    void draw(){System.out.println("Draw Circle"); }
}

class Triangle extends Shape
{
    void draw(){ System.out.println("Draw Three Lines"); }


class Line extends Shape
{
    void draw(){ System.out.println("Draw Line"); }
}

普通方法都是虚方法
三种非虚的方法:
static:以声明类型为准,与实例无关
private:子类看不见
final:子类不能被覆盖

虚方法和抽象方法 区别:
抽象方法不能实例化,强制派生类覆盖
虚方法可以覆盖也可以不覆盖
http://blog.youkuaiyun.com/jiangxinyu/article/details/6570232

4.动态类型确定

if( things[i] instanceof Integer )
布尔类型
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值