简析 Java语言的过载与重载

复习一下 :  过载 (override)     重载 (overload)  在代码实践中 理清概念。

 

package sub;

/**
 * 简析 过载与重载
 * User: yiminghe
 * Date: 2009-4-21
 * Time: 21:35:24
 */
public class ab {

    // 两个重载函数   - 1
    static void exe(Child c) {
        System.out.println("overload child");
    }

    // 两个重载函数   - 2
    static void exe(Parent c) {
        System.out.println("overload parent");
    }

    public static void main(String[] args) {
        Parent p = new Child();


        Child c = new Child();


        p.exe(c);

        //不能,静态查找,父类函数参数为子类
        //p.exe(p);

        // 可以 ,静态查找,子类函数参数为子类
        c.exe(p);


        //重载函数静态绑定
        exe(p);
        exe(c);
         
        //静态绑定,调用的仍然是Parent 的静态函数,不管p的动态类型
        p.exeStatic();

    }
}


class Parent {

    //过载函数基准,定义在父类
    Child exe(Child c) {
        System.out.println("child in parent");
        return null;
    }

    static exeStatic(){             
           System.out.println("child static  in parent");
    }
}


class Child extends Parent {

    //隐藏掉了父类静态函数,但不是override
    static exeStatic(){             
           System.out.println("child static  in parent");
    }
   
    //过载了父类的函数 ,返回值只能比 过载的父类函数返回类型更加严格(子类)

    GrandChild exe(Child c) {
        System.out.println("child in child");
        return null;
    }


    /*  下面过载错误: 过载了父类的函数 ,返回值只能比 过载的父类函数返回类型更加严格(子类)

其他还有 :
子类中重写的方法的访问权限不能比父类的低,如果父类的权限是public,则子类的该方法只能是public,父类的是protected,则子类的可以是protected或者public,依次类推。   
子类中的该方法不能比父类中的该方法抛弃(throws)更多种类的异常。

    Parent exe(Child c) {
        System.out.println("child in child");
        return null;
    }
    */


    //没有过载父类函数,重载了子类的同名函数

    void exe(Parent c) {
        System.out.println("parent in child");
    }

    /*
     下面重载错误:重载同类函数不考虑返回值 ,函数名和签名才是区别
    Parent exe(Parent c) {
        System.out.println("parent in child");
    }
    */
}

class GrandChild extends Child {

}



 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值