instanceof和类型转换

instanceof 判断一个对象是否是一个类的实例

编译不报错前提:两个类之间存在关系

核心父类引用指向子类对象

父类转子类 是引用类型的从高转低,需要强制转换

子类转父类,可能丢失一些自己本来的方法

代码示例 需认真理解

Person.java

package com.example.oop.demo03;

public class Person {
public String name;

public void say() {
System.out.println("person说了一句话");
}

public static void eat() {
System.out.println("person吃了一口饭");
}

public void run() {
System.out.println("person run");
}
}


Person.java

package com.example.oop.demo03;

public class Student extends Person {
public String name;
public String grade;

@Override
public void say() {
System.out.println("student说了一句话");
}

public static void eat() {
System.out.println("student吃了一口饭");
}
}


Teacher.java

package com.example.oop.demo03;

public class Teacher extends Person {
}


Application.java

package com.example.oop;

import com.example.oop.demo03.Person;
import com.example.oop.demo03.Student;
import com.example.oop.demo03.Teacher;

public class Application {
// 一个工程只有一个main方法
public static void main(String[] args) {
// 静态方法调用等式左边的类型,非静态方法调用看等式右边的类型
Student student = new Student();
Person person = new Student(); //父类引用指向子类对象
Object object = 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);// 编译错误

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(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

}
}