instanceof(类型转换)引用类型,判断一个对象是什么类型
在继承中,子类可以自动转型为父类,但是父类强制转换为子类时只有当引用类型真正的身份为子类时才会强制转换成功,否则失败
- 父类引用指向子类的对象
- 把子类转换为父类,向上转型:自动转换,丢失子类中原本可直接调用的特有方法
- 把父类转换为子类,向下转型:强制转换 ,会丢失父类被子类所重写掉的方法
- 方便方法的使用,减少重复的代码!简洁
package com.oop;
import com.oop.demo06.Student;
import com.oop.demo06.Person;
import com.oop.demo06.Teacher;
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);//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("====================================");
Teacher teacher = new Teacher();
//System.out.println(teacher instanceof Student); 编译出错
System.out.println(teacher instanceof Person);//true
System.out.println(teacher instanceof Object);//true
System.out.println(teacher instanceof Teacher);//true
//System.out.println(teacher instanceof String);编译出错
System.out.println("====================================");
String string = new String();
//System.out.println(string instanceof Student);编译出错
//System.out.println(string instanceof Person);编译出错
System.out.println(string instanceof Object);//true
//System.out.println(string instanceof Teacher);编译出错
System.out.println(string instanceof String);//true
}
}
package com.oop;
import com.oop.demo06.Person;
import com.oop.demo06.Student;
import com.oop.demo06.Person;
public class Application {
public static void main(String[] args) {
//类型之间的转换:基本类型自动转换
//高 低
Person obj = new Student();
//student将这个转换为Student类型,我们就可以使用Student类型的方法了
((Student)obj).go();
Student student=new Student();
student.run();
}
}