instanceof 是 Java 的保留关键字
import demo01.Person;
import demo01.Student;
import demo01.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 Object); // true
System.out.println(object instanceof Person); // true
System.out.println(object instanceof Student); // true
System.out.println(object instanceof Teacher); // false
System.out.println(object instanceof String); // false
/*
左边是对象,右边是类;当对象是右边类或父类所创建对象时,
返回true,否则,返false。
*/
System.out.println("========================");
Person person = new Student();
System.out.println(person instanceof Object); // true
System.out.println(person instanceof Person); // true
System.out.println(person instanceof Student); // 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 Object); // true
System.out.println(student instanceof Person); // true
System.out.println(student instanceof Student); // true
/*
System.out.println(student instanceof Teacher);
System.out.println(student instanceof String);
编译报错
*/
/*
instanceof左边显式声明的类型与右边操作元必须是同种类或存在继承关系,
否则会编译错误
*/
}
}
Person X = new Student;
System.out.println(X instanceof Y);
1,左边的 Person 是对象 X 的引用类型,右边的 Student 是实际类型,父类的引用可以指向子类
2,判断能否编译
看 X 的类型(就是引用类型 Person )是否和 Y 的类型是否存在父子关系,或同种类,存在即可编译
3,判断 true 还是 false
看 X 的实际类型(就是 Student)是否是 Y 的类型的子类,是就是 true 不是就是 false
类型转换
高 ---> 低:强制转换,(父类的字节容量大于子类的自己容量)
1,父类的引用指向子类的对象,相同的静态方法调用父类,非静态方法重写调用子类 2,子类转换父类,父类不能调用子类独有的方法 3,父类转换子类,需要强制转换
package demo01;
public class Student extends Person {
public void go() {
System.out.println("go");
}
}
package demo01;
public class Person {
public void run() {
System.out.println("run");
}
private void luo() {
System.out.println("l");
}
}
import demo01.Person;
import demo01.Student;
import demo01.Teacher;
public class Application {
public static void main(String[] args) {
Person a = new Student();
/*
a.go; 报错
Person 类里面没有这个 go 方法
需要进行转换类型
父类转子类,强制转换
*/
((Student) a).run();
// 子类转父类,自动转换
Student b = new Student();
Person c = b;
// c.go; 父类不能调用子类独有的方法
}
/*
1,父类的引用指向子类的对象,相同的静态方法调用父类,非静态方法重写调用子类
2,子类转换父类,父类不能调用子类独有的方法
3,父类转换子类,需要强制转换
*/
}
【【狂神说Java】Java零基础学习视频通俗易懂】https://www.bilibili.com/video/BV12J41137hu?p=72&vd_source=04c9e32408f61b4fd8bec53b61c24bd9