Java中的多态性和instanceof
2015-08-17 11:47
288 查看
一、多态性
将子类对象转换为父类称为“向上转型”,反之称为向下转型。
最后的实例中,People obj = new Teacher();中就是把子类Teacher转化成了父类而后赋值给父类变量的。向上转型是随意的,而向下转型不能随便转,只有经过向上转型的对象才可以向下转型。
当父类变量指向子类对象时,只能调用父类中独有的函数或者是被子类重载过的函数,不能调用子类中独有的函数,除非向下转型为原本的子类以后才可以,实例中有体现。
二、instanceof的使用
instanceof 是Java关键字之一,用于判断一个变量指向的对象的实际类型,返回值为true或者false。
用法: 变量名 instanceof 类名。
判断方法:当类名是变量实际指向的类或者是其父类时,返回true,否则为false。(注意:Java中父类变量可以指向子类对象,反之不可以)。返回值仅仅由变量指向的对象的类型决定而与变量类型无关。
实例:
输出结果为:
output of Teacher
-------------
output of Teacher
an_output of Teahcer
instance of people
instance of teacher
将子类对象转换为父类称为“向上转型”,反之称为向下转型。
最后的实例中,People obj = new Teacher();中就是把子类Teacher转化成了父类而后赋值给父类变量的。向上转型是随意的,而向下转型不能随便转,只有经过向上转型的对象才可以向下转型。
当父类变量指向子类对象时,只能调用父类中独有的函数或者是被子类重载过的函数,不能调用子类中独有的函数,除非向下转型为原本的子类以后才可以,实例中有体现。
二、instanceof的使用
instanceof 是Java关键字之一,用于判断一个变量指向的对象的实际类型,返回值为true或者false。
用法: 变量名 instanceof 类名。
判断方法:当类名是变量实际指向的类或者是其父类时,返回true,否则为false。(注意:Java中父类变量可以指向子类对象,反之不可以)。返回值仅仅由变量指向的对象的类型决定而与变量类型无关。
实例:
public class Main{ public static void main(String[] str){ People obj = new Teacher(); Teacher obj2; obj.output(); //obj.an_output();//会报编译错误 System.out.println("-------------"); obj2 = (Teacher)obj; obj2.output(); obj2.an_output(); if(obj instanceof People) System.out.println("instance of people"); if(obj instanceof Teacher) System.out.println("instance of teacher"); if(obj instanceof Student) System.out.println("instance of student"); return ; } } class People{ void output(){ System.out.println("output of People"); } } class Teacher extends People{ void an_output(){ System.out.println("an_output of Teahcer"); } void output(){ System.out.println("output of Teacher"); } } class Student extends People{}
输出结果为:
output of Teacher
-------------
output of Teacher
an_output of Teahcer
instance of people
instance of teacher
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树
- [原创]java局域网聊天系统