instanceof和类型转换
1.Instanceof作用
用来判断两个两个类之间是否存在父子关系 代码及详解如下: Application类代码点击查看代码
package com.Tang.oop.demo06;
public class Application {
public static void main(String[] args) {
//Object > String
//Object > Person > Student
//Object > Person > Teacher
Object object = new Student();
System.out.println(object instanceof Student);//true
System.out.println(object instanceof Person);//true
System.out.println(object instanceof Object);//true
System.out.println(object instanceof Teacher);//false
System.out.println(object instanceof String);//false
System.out.println("========================");
Person person = new Student();
System.out.println(person instanceof Student);//true
System.out.println(person instanceof Person);//true
System.out.println(person instanceof Object);//true
System.out.println(person instanceof Teacher);//false
// System.out.println(person instanceof String);编译就报错
System.out.println("========================");
Student student = new Student();
System.out.println(student instanceof Student);//true
System.out.println(student instanceof Person);//true
System.out.println(student instanceof Object);//true
//System.out.println(student instanceof Teacher);//编译报错
//System.out.println(student instanceof String);//编译报错
/*
总结:看编译能否通过主要是看对象左边的类型与instanceof 右边的类是否有父子关系
看运行结果为true或false主要是看对象所指向的引用(右边的类)与instanceof右边的类是否存在父子关系
*/
}
}
2.强制转换
Application类代码
点击查看代码
package com.Tang.oop.demo06;
public class Application {
public static void main(String[] args) {
Person person = new Student();
//Person相较于Student类是比较高的类,由高到低需要强制转换
//也就是将person对象强制转化为Student类,才能调用go方法
((Student)person).go();
Student student = new Student();
student.go();
//由低向高转则不需要强转,但是转化为高之后可能就会丢失一些方法
Person person1 = student;
// person1.go();
}
}
点击查看代码
package com.Tang.oop.demo06;
public class Student extends Person{
public void go(){
System.out.println("go");
}
}
点击查看代码
package com.Tang.oop.demo06;
public class Person {
public void run(){
System.out.println("run");
}
}