29_instanceof关键字和类型转换

09_instanceof关键字和类型转换

  1. instanceof用于判断对象和类的关系是否为父子
//Object>String
//Object>Person>Teacher
//Object>Person>Student
Object object = new Student();//引用object指向一个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
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);//false
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);//false
//System.out.println(student instanceof String);//false
  1. 类型转换
//高<------------------低,Person类型被限制使用Student类方法
Person student = new Student();
//强制转换student对象为Student类型
Student student1 = (Student) student;
student1.eat();
public class Student extends Person{

    @Override
    public void run() {
        System.out.println("Student run");
    }
    public void eat(){
        System.out.println("Student eat");
    }
}
public class Person {
    public void run(){
        System.out.println("person run");
    }
}

小提示

  1. 子类转换为父类,可能丢失自己的一些方法。
  2. 子类转换为父类,向上转型,自动转换。
  3. 父类转换成子类,向下转型,强制转换。
posted @ 2024-07-02 22:01  神莹  阅读(13)  评论(0)    收藏  举报