首页 > 其他分享 >instanceof和类型转换

instanceof和类型转换

时间:2023-01-20 11:23:07浏览次数:41  
标签:instanceof 类型转换 trueSystem System student println out

1.instanceof:判断类型是否相似

2.System.out.println(X instanceof Y);//能不能编译通过!取决于X和Y直接是否存在父子关系,有父子关系编译通过,无父子关系编译报错。

  X指向的类型是否是Y的子类型

eg:

  

//Object > String
//Object > Person > Teacher
//Object > Person > Student
Object object = new Student();
//System.out.println(X instanceof Y);//能不能编译通过!
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(student instanceof Student);//true
System.out.println(student instanceof Person);//true
System.out.println(student instanceof Object);//true
//System.out.println(student instanceof Teacher);//false
//System.out.println(student instanceof String);//false
System.out.println("==================================");



3.子类转换为父类,可能丢失自己的本来的一些方法!

4.父类引用指向子类的对象

  Person person = student;

5.把子类转换为父类,向上转型;

6.把父类转换为字类,向下转型;需要强制转换,可能会丢失方法

7.方便方法的调用,减少重复的代码!简洁

 

 

































标签:instanceof,类型转换,trueSystem,System,student,println,out
From: https://www.cnblogs.com/bqg2233/p/17062568.html

相关文章

  • JavaScript学习笔记—instanceof和hasOwn
    1.instanceof用来检查一个对象是否是一个类的实例检查的是对象的原型链上是否有该类实例(只要原型链上有该类实例,就会返回true)Object是所有对象的原型,所以任何对象和Ob......
  • python基础: 数据类型及其内置方法、类型转换
    目录基本数据类型数据类型的概述1.数据类型之整形--int2.数据类型之浮点型--float3.数据类型之字符型,也称字符串类型--str4.数据类型之列表--list5.数据类型之字典--dict6.......
  • MySQL查询精度丢失、varchar与bigint之间隐式类型转换的问题
    数据库查询过滤失效。今天在测试库上做一个关联查询时出现了捞出多余的值的情况,现在换个表名重现一下再解释。做项目时遇到一个奇怪的问题,关于mysql查询精度会有所丢失的......
  • 类型转换
    小容量可以自动转换为大容量,这种操作被称为:自动类型转换大容量转小容量,需要进行强制类型转换当一个整数赋值给一个char类型变量的时候,会自动转换成char字符型,最终的结果......
  • C/C++显示类型转换的位拓展方式
    最近用verilator写模块的tb,在这里卡了好久(测半天都是C++写的问题)要点变量从小位宽到大位宽显示类型转换(explicitcast)时的位拓展方式,取决于转换前变量的符号性。倘若......
  • python教程6--自定义函数,数据类型转换,解方程
    本文主要讲解点如下:简单函数数据类型转换空函数自定义绝对值函数自定义函数检查参数类型函数返回多个值求解ax2+bx+c=0的根具体代码如下:'函数相关'__author__='mo......
  • C语言中类型转换的两种方式
    类型转换1.定义:不同类型的数据混合运算时需要进行类型转换(conversion),将不同类型的数据转换成相同类型的数据后再进行计算。2.分类:(1)隐式类型转换*编译系统自动进行转换。*在......
  • java基础05 类型转换
    类型转换知识点上一节讲到,字符的本质还是数,所以字符也可以进行运算运算中,先要将不同类型的数据转换为同一类型后,才能再进行运算,转换具有优先级低—————————......
  • 类型转换
    1publicclassDemo03{2publicstaticvoidmain(String[]args){3/*4*由于java是强类型语言,所以有时要用到类型转换5*低......
  • C++ 扩展的显示类型转换
      ......