看看我是谁--Java instanceof 那些事儿

长辈们常说:人啊,什么时候都不能够忘本。

经过上两篇this和super的讲解,可以让自己知道什么调用自己的方法和成员,什么时候调用父类的方法和成员,那么对外人来说,如何区分一个对象到底是父类还是某个子类的实例呢?Java中关键字instanceof是专门为此而生的。当一个子类的实例赋值给一个父类的变量,这是Java多态的一种表现。而有时我们又想知道它到底是谁。

在this那一讲有个父类叫Student,super那一讲加了一个子类叫ClassLeader,今天在加一个子类叫生活委员吧,Lifeleader。Chinese英语只为做demo,勿怪。

public class LifeLeader extends Student
{
	private int fare;
	public LifeLeader(String name,String college,int fare)
	{
		super(name,college);
		this.fare = fare;
	}
	public void print()
	{
		super.print();
		System.out.println("fare is " + fare);
	}

	public static void main(String[] args)
	{
		Student linc = new LifeLeader("linc","shenyang",500);
		Student lily = new ClassLeader("class monitor","lily","shenyang");
		whoAreYou(linc);
		whoAreYou(lily);
	}

	public static void whoAreYou(Student student)
	{
		if(student instanceof ClassLeader)
		{
			System.out.println("this is ClassLeader!");
			student.print();
		}
		else if(student instanceof LifeLeader)
		{
			System.out.println("this is LifeLeader!");
			student.print();
		}
	}
}
编译运行:

D:\workspace\Java\project261\instance>javac -d . *java

D:\workspace\Java\project261\instance>java LifeLeader
construct
this student name is linc
this student name is linc college is shenyang
construct
this student name is lily
this student name is lily college is shenyang
this is LifeLeader!
name is: linc age is: 20 college is: shenyang
fare is 500
this is ClassLeader!
name is: lily age is: 20 college is: shenyang
duty is class monitor



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值