Java中的多态性和instanceof

一、多态性

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

最后的实例中,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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值