instanceof 类型转换

叁歲伎倆 2024-03-27 15:09 128阅读 0赞

instanceof (类型转换)引用类型 判断一个对象是什么类型

  1. 1. 父类引用指向子类对象
  2. 2. 把子类转化为父类,向上转型;
  3. 3. 把父类转化为子类,向下转型,强制转换
  4. 4. 方便方法的调用,减少重复的代码!简洁
  5. public class Application {
  6. public static void main(String[] args) {
  7. //Object-->String
  8. //Object-->Person-->Teacher
  9. //Object-->Person-->Student
  10. Object object = new Student();
  11. //System.out.println(x instanceof y);//会不会编译报错!要看有没有关系
  12. System.out.println(object instanceof Student);//true
  13. System.out.println(object instanceof Person);//true
  14. System.out.println(object instanceof Object);//true
  15. System.out.println(object instanceof Teacher);//false
  16. System.out.println(object instanceof String);//false
  17. System.out.println("===================================");
  18. Person person = new Student();
  19. System.out.println(person instanceof Student);//true
  20. System.out.println(person instanceof Person);//true
  21. System.out.println(person instanceof Object);//true
  22. System.out.println(person instanceof Teacher);//false
  23. //System.out.println(person instanceof String);//编译报错!
  24. System.out.println("===================================");
  25. Student student = new Student();
  26. System.out.println(student instanceof Student);//true
  27. System.out.println(student instanceof Person);//true
  28. System.out.println(student instanceof Object);//true
  29. //System.out.println(student instanceof Teacher);//编译报错!
  30. //System.out.println(student instanceof String);//编译报错!
  31. }
  32. }
  33. package com.oop;
  34. import com.oop.demo06.Person;
  35. import com.oop.demo06.Student;
  36. public class Application {
  37. public static void main(String[] args) {
  38. //类型之间的转化:父 子
  39. //高 低
  40. Person obj = new Student();
  41. //obj 将这个对象转化为Student类型,这样我们就能使用Student类型的方法了
  42. /* Student student = (Student) obj;
  43. student.go();*/
  44. ((Student)obj).go();
  45. //子类转化为父类,可能丢失自己本来的一些方法
  46. Student student = new Student();
  47. Person person = student;
  48. }
  49. /*
  50. 1. 父类引用指向子类对象
  51. 2. 把子类转化为父类,向上转型;
  52. 3. 把父类转化为子类,向下转型,强制转换
  53. 4.方便方法的调用,减少重复的代码!简洁
  54. */
  55. }
  56. package com.oop.demo06;
  57. public class Student extends Person{
  58. public void go(){
  59. System.out.println("go");
  60. }
  61. }
  62. package com.oop.demo06;
  63. public class Person {
  64. public void run() {
  65. System.out.println("run");
  66. }
  67. }

发表评论

表情:
评论列表 (有 0 条评论,128人围观)

还没有评论,来说两句吧...

相关阅读