温故而知新--java的多态

温故而知新:
java的重写,重载和动态链接构成多态性。
class child extends class father{}
father F = new child(); //定义了一个父类类型的应用F指向子类对象child
child C = (child)new father;//error, father can't be cast to child
父类类型的引用F可以调用父类中定义的所有属性和方法,对于子类中定义而父类中没有定义的方法,F不能访问。
父类中定义的方法被子类重写,则父类类型引用将会调用子类中的方法,这就是动态链接。(final,static,private 方法除外)
属性/变量没有多态的概念(父类,子类可以有重名的变量),final,static和private方法也没有多态的概念。
一起来看一个例子:可以直接拷贝到inheritance.java编译运行:
javac inheritance.java
java inheritance
运行结果见注视部分!
 
import java.io.OutputStream;
class father {
    public int i = 1;
    void funcA(){
        System.out.println("father-funcA");
   
        funcB();
    }
    void funcB(){
        System.out.println("father-funcB");
    }
    static void funcC(){
        System.out.println("father-funcC");
    }
}
class child extends father {
    public int i = 2;
    void funcA(int a){
        System.out.println("child-funcA");
    }
    void funcB(){
        System.out.println("child-funcB");
    }
    static void funcC(){
        System.out.println("child-funcC");
    }
}
public class inheritance {
public static void main(String args[]) {
   
    child C = new child();
    C.funcA();  //father-funcA child-funcB
    C.funcB();  //child-funcB
    C.funcC();  //child-funcC
    System.out.println(C.i); //2
   
    father F = new child();
    F.funcA();  //father-funcA child-funcB
    F.funcB();  //child-funcB
    F.funcC();  //father-funcC
    System.out.println(F.i); 1
    //F.funcA(5); //error funcA(int) not define in father
   
    father F2 = C;
    F2.funcA(); //father-funcA child-funcB
    F2.funcB(); //child-funcB
    F2.funcC(); father-funcC
    System.out.println(F.i); 1
    //F2.funcA(5); //error funcA(int) not define in father
   
    child C2 = (child)(new father()); //father can not be cast to child
    C2.funcA();
    C2.funcB();
    C2.funcC();
    System.out.println(C2.i);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值