instanceof和类型转换
在多态里我们会发现instanceof和强制转换这两种类型。
instanceof
判断一个对象是什么类型
package com.mjh.oop.demo05;
public class Impl {
public static void main(String[] args) {
Object object=new Student();
/**
* Student 继承 Person
* Object > String
* Object > Person>Teacher
* Object > Person>Student
*
* System.out.println(X instanceof Y);主要是看XY之间是否存在父子关系(否为false,是为true)
*/
System.out.println(object instanceof Student);//true
System.out.println(object instanceof Person);//true
System.out.println(object instanceof Teacher);//false
System.out.println(object instanceof String);//false
System.out.println("==============================================");
Person person=new Student();
System.out.println(person instanceof Student);//true
System.out.println(person instanceof Person);//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 Student);//true
System.out.println(student instanceof Person);//true
//System.out.println(student instanceof Teacher);//编译错误,同一级不能比较
System.out.println(object instanceof String);//false
}
}
类型转换
public static void main(String[] args) {
//类型之间的转化 父 子关系
Person p=new Student();
//将p转换student类型就可以使用student方法了
((Student) p).eat();//高—--->低
public static void main(String[] args) {
//类型之间的转化 父 子关系
Student s=new Student();
//子类转换为父类,可能丢失自己本来的一些东西
s.eat();
Person p=s;//低---->高 默认转换
// p.eat();//编译不通过
父类引用指向子类对象
把子类转换为父类 ,向上转型
把父类转换为子类,向下转型 强制转换
方便方法的调用,减少重复的代码
核心:就是抽象;封装,继承,多态, 抽象, 接口,越来越抽象