instanceof

引用类型,类型转换

  • 判断某一个对象是不是某个类型的类的实例(有关系才能比较,否则会报错)

  • 能不能编译通过,取决于X与Y是否存在父子关系

例子:父类代表高类,子类代表低类

Object > Persion > 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
  • objectStudent 类的实例,所以 object instanceof Studenttrue
  • Student 类继承自 Person,所以 object instanceof Persontrue
  • Student 类间接继承自 Object(通过 Person 或直接),因此 object instanceof Objecttrue

这意味着 object 同时满足以下条件:

  • 它是 Student 类的实例。
  • 它也是 Person 类的实例,因为 Student 继承了 Person
  • 它也是 Object 类的实例,因为所有类都继承自 Object

关键在于等号右侧的内容,也就是通过 new 关键字创建的对象实例。这部分决定了对象的实际类型,instanceof 运算符的结果也是基于这个实际类型来判断的。

无论 object 被声明为哪种引用类型,instanceof 运算符总是根据 object 的实际类型(由 new 创建的类型)来进行判断。

类之间的类型转换

父类可以自动转化为子类,但不能调用子类独有的方法(即使父类的实际实例是子类),这时就需要强制类型转化

	Person student = new Student();
	Student st1 = new Student();
	Person person = st1;

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

Static

  • Static属性:所有类的实例对象以及类公用

  • Static方法:静态方法可以调用静态方法,非静态方法可以调用静态方法,但是静态方法不能调用非静态方法

静态代码块:在程序运行最开始只执行一次

static{
	//静态代码块
}

静态导入包

导入某一个方法

import static java.lang.Math.random;

通过 'final' 修饰的类无法被继承