• java中的instanceof 的用法


    1.instanceof功能:判断前面的对象是否属于后面的类,或者属于其子类;如果是,返回 true,不是返回 false

    2.instanceof概念是在多态中提出的

    3.注意事项:
    使用 instanceof 时需要保证:
    instanceof 前面的引用变量编译时的类型要么与后面的类型相同,要么与后面的类型具有父子继承关系,否则就会出现编译出错。

    4,代码案例:

    1. //Student类
    2. package demo07;
    3. public class Student extends Person{
    4. public void go(){
    5. }
    6. }
    7. //Person类
    8. package demo07;
    9. public class Person {
    10. public void run(){
    11. System.out.println("run");
    12. }
    13. }
    14. //输出
    15. import demo07.Person;
    16. import demo07.Teacher;
    17. import demo07.Student;
    18. public class Application {
    19. public static void main(String[] args) {
    20. //System.out.println(X instanceof Y );能不能编译通过!
    21. //object>String
    22. //object>Person>Teacher
    23. //object>Person>Student
    24. Object object =new Student();
    25. System.out.println(object instanceof Student);//true
    26. System.out.println(object instanceof Person);//true
    27. System.out.println(object instanceof Object);//true
    28. System.out.println(object instanceof Teacher);//False
    29. System.out.println(object instanceof String);//False
    30. System.out.println("========================");
    31. Person person = new Student();
    32. System.out.println(person instanceof Student);//true
    33. System.out.println(person instanceof Person);//true
    34. System.out.println(person instanceof Teacher);//False
    35. //System.out.println(person instanceof String);// 编译报错
    36. System.out.println("==================");
    37. Student student = new Student();
    38. System.out.println(student instanceof Student);//true
    39. System.out.println(student instanceof Person);//true
    40. System.out.println(student instanceof Object);//true
    41. //System.out.println(student instanceof Teacher);//编译报错
    42. //System.out.println(student instanceof String);//编译报错
    43. System.out.println("==================");
    44. //类型之间的转换 父 子
    45. Person student1 = new Student();
    46. //student1.go();
    47. //将student这个对象转换成Student这个类型,然后就可以使用Student类型的方法了
    48. Student student11 = (Student) student1;//快捷键,(Student,要转换的类型)student,需要转换的对象 然后Alt+回车
    49. student11.go();
    50. Student student2 = new Student();
    51. //子类转换为父类,可能会丢失一些自己本来的方法
    52. student2.go();
    53. Person person1 =student2;
    54. //person1.go();
    55. }
    56. }

  • 相关阅读:
    英语翻译软件-批量自动免费翻译软件支持三方接口翻译
    java 调用C#语言写的dll文件代码 超详细过程
    C#描述-计算机视觉OpenCV(5):直方图算法
    JMETER也会遇到加密难题,中文乱码也能一并处理
    空中计算(Over-the-Air Computation)学习笔记
    SpringCloud - Spring Cloud Alibaba 之 Seata分布式事务服务详解;部署(十八)
    一天完成react面试准备
    如何恢复u盘删除文件?2023最新分享四种方法恢复文件
    SpringCloud之Sentinel入门
    城中村智能水电表改造,提升居民生活品质
  • 原文地址:https://blog.csdn.net/2301_79221593/article/details/134480228