• 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. }

  • 相关阅读:
    移动端web调试工具vConsole使用详解
    vscode配置openssl include和lib环境(M1 mac)
    进程的认识
    Codeforces Round #813 (Div. 2) A~C
    435. 无重叠区间
    竣达技术丨室内空气环境监测终端 pm2.5、温湿度TVOC等多参数监测
    OpenCV-Python学习(15)—— OpenCV 图像旋转角度计算(NumPy 三角函数)
    JS测试出最小支持字体,以及修复PDFJS的文本错误偏移
    【C++】STL详解(八)—— priority_queue的使用及模拟实现&&仿函数
    三维穿墙雷达 该如何选择
  • 原文地址:https://blog.csdn.net/2301_79221593/article/details/134480228