欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java之instanceof,

来源: javaer 分享于  点击 12477 次 点评:280

Java之instanceof,


instanceof 运算符         判断该对象是否是某一个类的实例

语法格式                 boolean  b = 对象 A  instanceof 类B ;//判断A对象是否是B类的实例,如果是,返回true

instanceof 运算符

若对象是类的实例返回true

若对象是类的父类的实例也返回true

//父类
class Person
{
	String name;
	int age;
	public void work()
	{
		System.out.println("不知道工作干什么");
	}
}
//子类Student
class Student extends Person
{
	public void work()
	{
		System.out.println("我的工作就是上课认真听讲老师");
	}
}
class Teacher extends Person
{
	public void work()
	{
		System.out.println("我的工作就是认真给同学讲课");
	}
}

class Combine
{
	public void work(Person p)
	{
		if(p instanceof Student)
		{
			Student stu = new Student();
			stu.work();
		}
		else
		{
			Teacher tea = new Teacher();
			tea.work();
		}
	}
}
public class Demo {

	public static void main(String[] args) {
		
		//创建学生对象
		Person p = new Student();
		Combine com = new Combine();
		com.work(p);
		p = new Teacher();
		com.work(p);
		
	}
}


相关文章

    暂无相关文章
相关栏目:

用户点评