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

instanceof和类型转换

时间:2023-03-20 20:47:32浏览次数:36  
标签:instanceof 类型转换 student System Student println out

  1. 类型转换
    •  父类引用转向子类对象
    • 把子类转换为父类,向上转型
    • 把父类转换为子类,向下转型,强制转换
    • 方便方法的调用
    public static void main(String[] args) {
//instanceof
// Object->Person->Student
// Object object=new Student();
// System.out.println(object instanceof Student);
// System.out.println(object instanceof Person);
// System.out.println(object instanceof Object);
// System.out.println(object instanceof Teacher);
// System.out.println(object instanceof String);

//Person->Student
// Student student=new Student();
// System.out.println(student instanceof Student);
// System.out.println(student instanceof Person);
// System.out.println(student instanceof Object);
// System.out.println(student instanceof Teacher);

Person person1=new Student(); //父亲--->>子类
//person将这个对象转化为Student类型,我们就可以使用Student类型的方法了
Student student= (Student) person1;
student.eat();

((Student) person1).eat();
//子类转父类可能丢失原来子类的方法
// Student student1=new Student();
// Person person=student1;
//person.eat;//无法再调用自己的eat

标签:instanceof,类型转换,student,System,Student,println,out
From: https://www.cnblogs.com/twz1015/p/17237655.html

相关文章

  • 【多态】中的【instanceof】
    /***Bysleeon2023/3/20*父类引用指向子类对象,这个引用既属于子类,又属于父类*但是如果各自创建对象的话,父类对象就不属于子类*/publicclassTest{pub......
  • 数据类型转换、运算符
    day02数据类型太简单,没啥写的,略注意:空串""是长度为0的字符串。空串是一个Java对象,有自己的串长度(0)和内容(空)。不过,String变量还可以存放一个特殊的值,名为null,这表示目前......
  • java类型转换方式
    java类型转换方式mapstruct并不好用,代码臃肿,性能高一点参考https://blog.csdn.net/WX5991/article/details/121936717......
  • mysql 隐式类型转换规则
    规则:1、两个参数至少有一个是NULL时,比较的结果也是NULL,例外是使用<=>对两个NULL做比较时会返回1,这两种情况都不需要做类型转换2、两个参数都是字符串,会按照字符串......
  • 类型转换
    C#中类型转换分为两种:隐式转换和显示转换。隐式转换将一个较小范围的数据类型转换为较大范围的数据类型时,编译器会自动完成类型转换。显示转换将一个较大范围的数据类型......
  • 指针类型转换:reinterpre_cast
    指针类型转换:reinterpre_cast//用于指针类型之间的转换//用于整数和指针类型的转换//原理是直接从二进制位进行复制,是一种极其不安全的转换int*p=reinterpre_cas......
  • 隐式类型转换
    隐式类型转换给无符号类型赋予一个超出其范围的初始值时,就会发生隐式类型转换含有无符号类型的表达式,也会发生隐式类型转换unsignedchar=-1;//unsignedintu=......
  • 静态类型转换:static_cast
    静态类型转换:static_cast//用于基本类型的转换,即内置类型,但不可用于基本类型指针的转换inta=10;int*pi=&a;char*pc=static_cast<char*>(pi);//错误,不可用......
  • 常类型转换:const_cast
    常类型转换:const_cast//用于移除对象的const属性//通常不是为了修饰对象,而是为了给函数传参时函数可以接受该对象constint&ref=1;//ref的值不可修饰int&ref1......
  • js判断是否是字符串 instanceof
    exportfunctionisString(str){if(typeofstr==="string"||strinstanceofString){returntrue}returnfalse}conststr=newString('hello'......