您的位置:首页 > 编程语言 > Java开发

Java中的多态性和instanceof

2015-08-17 11:47 288 查看
一、多态性

将子类对象转换为父类称为“向上转型”,反之称为向下转型。

最后的实例中,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 多态性 instanceof