首页 > 其他 > 详细

instanceof和类型转换

时间:2021-02-13 08:30:37      阅读:27      评论:0      收藏:0      [点我收藏+]

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,高转低需要强制转换。
		
	}
}

instanceof和类型转换

原文:https://www.cnblogs.com/chibadream/p/14399138.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!