复习一下 : 过载 (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 {
}