前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java上转型和下转型(对象的多态性)

java上转型和下转型(对象的多态性)

作者头像
用户3030674
发布2018-09-14 14:54:56
2.1K1
发布2018-09-14 14:54:56
举报

/*上转型和下转型(对象的多态性) *上转型:是子类对象由父类引用,格式:parent p=new son *也就是说,想要上转型的前提必须是有继承关系的两个类。 *在调用方法的时候,上转型对象只能调用父类中有的方法,如果调用子类的方法则会报错 *下转型:是父类向下强制转换到子类对象 *前提是该父类对象必须是经过上转型的对象。 * *代码示例:*/

代码语言:javascript
复制
 1 abstract class Parent{
 2     abstract void grow();
 3 }
 4 class Son extends Parent{
 5     void grow(){
 6         System.out.println("我比父亲成长条件好");
 7     }
 8     void dance(){
 9         System.out.println("我会踢球");
10     }
11 }
12 public class test {
13     public static void main(String[] args) {
14         //上转型,用父类的引用子类的对象
15         Parent p=new Son();
16         //调用父类中有的方法
17         p.grow();
18         //p.dance();这里会报错,因为父类中没有dance()方法
19         
20         //对进行过上转型的对象,进行强制下转型
21         Son s=(Son)p;
22         //调用子类中的方法
23         s.dance();
24     }
25 }

/* * 在我们写程序中,很少会把代码写死,比如说还会有daughter类 * 然后在封装函数来调用对象,说不定会用到子类的方法,这里我们来讲解一下这一方面的知识*/

代码语言:javascript
复制
 1 abstract class Parent{
 2     abstract void grow();
 3 }
 4 class Son extends Parent{
 5     void grow(){
 6         System.out.println("我比父亲成长条件好一点:son");
 7     }
 8     void play(){
 9         System.out.println("我会踢球");
10     }
11 }
12 class Daughter extends Parent{
13     void grow(){
14         System.out.println("我比父亲成长条件好很多:daughter");
15     }
16     void dance(){
17         System.out.println("我会跳舞");
18     }
19 }
20 public class test {
21     public static void main(String[] args) {
22         Parent p=new Son();
23         show(p);
24         Parent p2=new Daughter();
25         show(p2);
26     }
27     public static void show(Parent p){
28             //现将父类中有的方法输出
29             p.grow();
30             //对进行过上转型的对象进行类型判断,然后进行相应的强制下转型
31             if(p instanceof Son){
32                 //判断是哪个类的上转型对象,然后进行下转型
33                 Son s=(Son)p;
34                 //调用子类中的方法
35                 s.play();
36             }else if(p instanceof Daughter){
37                 Daughter d=(Daughter)p;
38                 d.dance();
39             }
40             
41     }
42 }

/* * 在上转型中,编译程序的时候,看父类中有没有对象调用的方法,没有的话,就报错 * 例如:Parent p=new Son(); * p.play(); * play()方法在父类中没有,所以会报错 * 在运行的时候,看子类中是否有调用的方法,有的话,运行子类的方法(重写父类的方法) * * */

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2014-12-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档