面对对象13:instanceof 和 类型转换

1.instanceof (类型转换)引用类型,判断一个对象时什么类型(即判断两个类直接是否具有父子关系)

2.instanceof是Java中的二元运算符,左边是对象,右边是类;当对象是右边类或子类所创建对象时,返回true;否则,返回false。

这里说明下:

  • 类的实例包含本身的实例,以及所有直接或间接子类的实例

  • instanceof左边显式声明的类型与右边操作元必须是同种类或存在继承关系,也就是说需要位于同一个继承树,否则会编译错误

package com.oop;

import com.oop.demo05.A;
import com.oop.demo05.B;
import com.oop.demo06.Person;
import com.oop.demo06.Student;
import com.oop.demo06.Teacher;
import java.lang.String;


public class Application {
    public static void main(String[] args) {

        //Object > String
        //Object > Person > Teature
        //Object > Person > Student
        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
        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 Object);//true
        System.out.println(person instanceof Teacher);//false
        //System.out.println(person instanceof String);//报错
        System.out.println("===========================================");

        Student student = 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


    }
}

2.强制转换

public class Application {
    public static void main(String[] args) {
        //类型之间的转化:父   子
        
        //高                   低
        Person obj = new Student();
        //obj.go();//报错
        //student将这个对象转换为Student类型,我们就可以使用Student类型的方法了!
        Student student= (Student)obj;//这样就可以使用子类的方法了,这里是把父类强行转换为子类
        student.go();
        
        //子类转化为父类,可能丢失自己本来的一些方法!
        Student student1 = new Student();
        student1.go();
        Person person = student1;
        //person.go();//报错
        
        
   /*
   1.父类引用指向子类的对象
   2.把子类转换为父类,向上转型
   3.把父类转换为子类,向下转型;强制转换
   4.方便方法的调用,减少重复的代码!
   
   抽象:封装;继承;多态。
        
    */
        
        
        


    }
}

 

posted @ 2024-04-02 15:06  三口一头居  阅读(19)  评论(0)    收藏  举报