java

来源:互联网 发布:数据库except 编辑:程序博客网 时间:2024/06/05 20:05
接口实现、继承等关系的运用案例
P.S: 强制转换,看引用变量指向的对象与目标数据间的关系。
可运用 "引用变量 instanceof 目标数据" 来判断是否可用强转
 1 package com.implementdemo; 2  3 /*接口实现、继承等关系的运用*/ 4 public class ImplementDemo { 5     public static void main(String[] args){ 6         Abs x = new Aoo(); 7  8         /* 9         Aoo xx = (Aoo)x;  //可完全访问Aoo,强转10         x.b();11         xx.a();12         x.a();13         */ //无法访问14 15         /*16          * 强制转换,看引用变量指向的对象,17          * 即是看该对象与目标数据之间的关系18          * */19         if(x instanceof Boo){20             Boo xx = (Boo) x;21             xx.b();22             xx.num2 = 5;  //ClassCastingException 类型转换异常23         }24 25         if(x instanceof Inter1){26             Inter1 xx =(Inter1) x;27             xx.a();28         }29 30         Inter1 y = new Aoo();  //向上造型31     }32 }33 34 interface Inter1{35     abstract void a();36 }37 abstract class Abs{38     public abstract void b();39 }40 41 class Aoo extends Abs implements Inter1{42     int num1;43     public void a(){44         System.out.println("a");45     }46     public void b(){47         System.out.println("b");48     }49 }50 class Boo extends Abs {51     int num2;52     public void b(){}53 }

 

原创粉丝点击