码迷,mamicode.com
首页 > 其他好文 > 详细

4-多态

时间:2017-01-17 21:22:05      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:界面   start   向上转型   open   exp   package   code   pre   public   

1.多态性的体现:

方法的重载和重写

对象的多态性

2.对象的多态性:

向上转型:程序会自动完成

              父类 父类对象 = 子类实例

向下转型:强制类型转换

              子类 子类对象 = (子类)父类实例

技术分享
 1 package com.example;
 2 class A{
 3     public void tell1(){
 4         System.out.println("this is Atell1");
 5     }
 6     public void tell2(){
 7         System.out.println("this is Atell2");
 8     }
 9 }
10 
11 class B extends A{
12     public void tell1(){
13         System.out.println("this is Btell1");
14     }
15     public void tell3(){
16         System.out.println("this is Btell3");
17     }
18 }
19 
20 public class MyClass {
21     public static void main(String[] args){
22         //有个错误以后会经常遇到:ClassCastException
23         //向上转型
24 //        B b = new B();
25 //        A a = b;
26 //        a.tell1();
27 //        a.tell2();
28         //向下转型
29 
30         B b = new B();
31         A a = b;
32 
33         B b2 = (B)a;
34         b2.tell1();
35         b2.tell3();
36         b2.tell2();
37 
38 
39     }
40 }
View Code

 

3.多态存在的三个必要条件:

(1)继承

(2)重写

(3)父类引用指向子类对象

技术分享
 1 package com.example;
 2 
 3 class A{
 4     void tell1(){
 5         System.out.println("this is A-tell1");
 6     }
 7 }
 8 
 9 class B extends A{
10     void tell1(){
11         System.out.println("this is B-tell2");
12     }
13 }
14 
15 class C extends A{
16     void tell1(){
17         System.out.println("this is C-tell3");
18     }
19 }
20 
21 public class MyClass {
22     public static void main(String[] args){
23         say(new B());
24         say(new A());
25     }
26 
27     public static void say(A a){
28         a.tell1();
29     }
30 }
View Code

 

4.多态的理解:

比方说按下F1这个动作,如果当前在flash界面下弹出的就是AS 3 的帮助文档;如果当前在word界面下弹出就是Word帮助;在Windows界面下弹出的是Windows帮助和支持。同一事件发生在不同的对象上会产生不同的结果。

5.Java中多态的实现方式:

(1)接口实现

(2)继承父类进行方法重写

(3)同一个类中进行方法重载

 

4-多态

标签:界面   start   向上转型   open   exp   package   code   pre   public   

原文地址:http://www.cnblogs.com/BelieveFish/p/6294461.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!