instanceof和类型转换

instanceof

  • 判断对象类型是不是父子关系
public class Person
{
}
public class Student extends Person
{
}
public class Teacher extends Person
{
}
public class Application
{
	public static void main(String[] args){
		//Object>Person>Student
		//Object>Person>Teacher
		//Object>String
		Object object = new Student();
		System.out.println(object instanceof Student);//ture
		System.out.println(object instanceof Person);//ture
		System.out.println(object instanceof Object);//ture
		System.out.println(object instanceof Teacher);//false
		System.out.println(object instanceof String);//false
		
	}
}
  • 注意:同级之间不能比较
public class Application
{
	public static void main(String[] args){
		//Object>Person>Student
		//Object>Person>Teacher
		//Object>String
	 Student object = new Student();//数据类型变为Student,与Teacher无法比较
		System.out.println(object instanceof Student);//ture
		System.out.println(object instanceof Person);//ture
		System.out.println(object instanceof Object);//ture
		System.out.println(object instanceof Teacher);//false
		System.out.println(object instanceof String);//false
		
	}
}

类型转换

  • 低转高,自动转换;高转低,强制转换
public class Student extends Person
{
	public void go(){
		System.out.println("go");
	}
}
public class Application
{
	public static void main(String[] args){
		Person human = new Student();
		((Student)human).go();//human.go ()由Person转为Student,高转低需要强制转换。
		
	}
}
上一篇:30岁开始学java,第一次记录


下一篇:运算符的优先级