多态与转型

多态

父类中的方法被子类重写时,可以产生不同的功能行为

编译时多态,运行时多态(运行时,根据对象的具体类型不同来决定调用什么形式的方法

实质便是自动类型的提升

例如: father chd = new child(); (自动向上转型,堆中存储的是子类地址),子类中的特定方法无法访问,但注意的是父类中的方法可以被子类中的方法覆盖,当向上转型的对象调用方法时,便会有三种情况:1父类有方法,子类有覆盖方法:编译通过,执行子类方法。

2父类有方法,子类没覆盖方法:编译通过,执行父类方法(子类继承)。

3父类没方法,子类有方法:编译失败,无法执行。

向上转型:不能访问子类的特有函数或者是新增变量(覆盖变量也不行)等等,向上塑造型只是针对成员函数的。

向下转型:能访问子类的特有函数或者是变量等等,如上述可进行向下转型:child chd2=(child) chd;

 

虽然定义的对象的father的,但实际内存是指向其子类,在调用chd的函数方法是会先去访问子类

 注意:子类中不允许存在和父类方法同名同参数,但是类型却不同的方法(一个int,一个double之类的)

 

 1 package lessons;
 2 
 3 public class father {
 4     father(){
 5         
 6     }
 7     int c=5;
 8     final int d=8;
 9     void show(){
10     System.out.println("it is father");
11     }
12     int axe(){
13         return 5;
14     }
15 }
16 
17 class child extends father{
18     int a=9,b=8; int c=9;
19     public static void main(String[] args){
20         //father chd=new child();
21         father chd=new child();
22         child chd2=(child)chd;
23         chd2.hello_world();
24         chd.show();
25         System.out.println(chd.c);//向上塑造只针对成员函数
26         System.out.println(chd2.c);
27     }
28     void show(){
29         System.out.println("it is child");
30         super.show();
31     }
32     //double   //不允许存在
33     //axe(){
34         //return 8;
35 //}
36     void hello_world(){
37         System.out.println("hello,here");
38     }
39 }

输出结果:hello,here
it is child
it is father
5
9

 

 

posted @ 2020-04-23 17:54  良夜  阅读(162)  评论(0编辑  收藏  举报