• springboot04- instanceof和类型转换


    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();//编译不通过
    

    父类引用指向子类对象

    把子类转换为父类 ,向上转型

    把父类转换为子类,向下转型 强制转换

    方便方法的调用,减少重复的代码

    核心:就是抽象;封装,继承,多态, 抽象, 接口,越来越抽象

  • 相关阅读:
    利用百度搜集子域名--爬虫技巧
    IoC模式
    SpringMVC @RequestBody接收Json对象字符串
    用eclipse创建动态web项目手动生成web.xml方法
    1.Java Spring MVC入门 安装
    获取所有注解
    带参数的方法获取注解
    利用反射调用注解
    java枚举类型
    java创建多线程
  • 原文地址:https://www.cnblogs.com/mjjh/p/13280815.html
Copyright © 2020-2023  润新知