[Java]instanceof关键字

class Person {
	private String name;
	private int age;
	String sex = "secret";
	protected Person(String name, int age) {
		this(name);
		this.age = age;
		System.out.println("Father constructor 1th");
	}
	
	protected Person(String name) {
		this.name = name;
		System.out.println("Father constructor 2th");
	}
	
	protected String getName() {
		return name;
	}
	protected void setName(String name) {
		this.name = name;
	}
	protected int getAge() {
		return age;
	}
	protected void setAge(int age) {
		this.age = age;
	}
	protected String say () {
		return (this.name+" is saying sth");
	}
	
	public String getOldSex() {
		return sex;
	}
	
	public Person getCurrentObj () {
		return this;
	}
}

class Student extends Person {
	String sex = "male ";
	public Student(String name, int age) {
		super(name, age);
		System.out.println("child constructor 2th");
		// TODO Auto-generated constructor stub
	}
	
	public String getSex() {
		return sex;
	}
	
	public Student(String name) {
		super(name);
		System.out.println("child constructor 1th");
	}

	private String school;

	public String getSchool() {
		return school;
	}

	public void setSchool(String school) {
		this.school = school;
	}
	
	public String say() {
		return "super.say() = "+super.say()+"\n"+this.getName() + " said something"+"\n"+"super.sex = "+super.sex;
	}
	
	public String stuUnique () {
		return "unique method of Student";
	}

}
public class T2 {
	
	public static void main(String [] args) {
		Person p = new Person("Xiaoming", 21);
		Student stu = new Student("stu", 15);
		System.out.println("p instanceof Person "+(p instanceof Person));
		System.out.println("stu instanceof Student "+(stu instanceof Student));
		Person xiaohong = new Student("xiaohong", 19);
		System.out.println("xiaohong instanceof Student "+(xiaohong instanceof Student));
		System.out.println("xiaohong instanceof Person "+(xiaohong instanceof Person));
		Student xiaohongdown = (Student)xiaohong;
		System.out.println("xiaohongdown instanceof Student "+(xiaohongdown instanceof Student));
		System.out.println("xiaohongdown instanceof Student "+(xiaohongdown instanceof Person));		
		System.out.println("p instanceof Student "+(p instanceof Student));
		System.out.println("p instanceof Person "+(p instanceof Person));
		
	}
}

运行结果:

结果分析:

p是一个Person类的实例,属于基类的实例

stu是一个子类Student的实例

xiaohong是一个Student对象向上转型得到的一个Person对象

根据输出结果这个对象既是Student对象,又是Person对象

xiaohongdown是一个xiaohong向下转型得到的Student对象

此时依然同时是Student和Person的对象

但是如果使用Person 对象 p就会发现,p只是Person类的实例

不是子类Student的实例

所以子类对象可以向上转型,然后又向下转型

但是父类的对象不能向下转型

猜你喜欢

转载自blog.csdn.net/chenhanxuan1999/article/details/91878892