instanceof和类型转换

打印 上一主题 下一主题

主题 896|帖子 896|积分 2688

1.Instanceof作用

    用来判断两个两个类之间是否存在父子关系代码及详解如下:Application类代码点击查看代码
  1. package com.Tang.oop.demo06;
  2. public class Application {
  3.     public static void main(String[] args) {
  4.         //Object > String
  5.         //Object > Person > Student
  6.         //Object > Person > Teacher
  7.         Object object = new Student();
  8.         System.out.println(object instanceof Student);//true
  9.         System.out.println(object instanceof Person);//true
  10.         System.out.println(object instanceof Object);//true
  11.         System.out.println(object instanceof Teacher);//false
  12.         System.out.println(object instanceof String);//false
  13.         System.out.println("========================");
  14.         Person person = new Student();
  15.         System.out.println(person instanceof Student);//true
  16.         System.out.println(person instanceof Person);//true
  17.         System.out.println(person instanceof Object);//true
  18.         System.out.println(person instanceof Teacher);//false
  19.        // System.out.println(person instanceof String);编译就报错
  20.         System.out.println("========================");
  21.         Student student = new Student();
  22.         System.out.println(student instanceof Student);//true
  23.         System.out.println(student instanceof Person);//true
  24.         System.out.println(student instanceof Object);//true
  25.         //System.out.println(student instanceof Teacher);//编译报错
  26.         //System.out.println(student instanceof String);//编译报错
  27.         /*
  28.             总结:看编译能否通过主要是看对象左边的类型与instanceof 右边的类是否有父子关系
  29.             看运行结果为true或false主要是看对象所指向的引用(右边的类)与instanceof右边的类是否存在父子关系
  30.          */
  31.     }
  32. }
复制代码
此时Student和Teacher类只是都继承了Person类所以并没有什么代码,就不在分别展示
2.强制转换

Application类代码
点击查看代码
  1. package com.Tang.oop.demo06;
  2. public class Application {
  3.     public static void main(String[] args) {
  4.         Person person = new Student();
  5.         //Person相较于Student类是比较高的类,由高到低需要强制转换
  6.         //也就是将person对象强制转化为Student类,才能调用go方法
  7.         ((Student)person).go();
  8.         Student student = new Student();
  9.         student.go();
  10.         //由低向高转则不需要强转,但是转化为高之后可能就会丢失一些方法
  11.         Person person1 = student;
  12.         // person1.go();
  13.     }
  14. }
复制代码
Student类代码点击查看代码
  1. package com.Tang.oop.demo06;
  2. public class Student extends Person{
  3.     public void go(){
  4.         System.out.println("go");
  5.     }
  6. }
复制代码
Person类代码点击查看代码
  1. package com.Tang.oop.demo06;
  2. public class Person {
  3.     public void run(){
  4.         System.out.println("run");
  5.     }
  6. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

钜形不锈钢水箱

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表