instanceof和类型转换

instanceof

父类Person;子类Student;子类Teacher;测试类Application

package com.oop.Demo05;

public class Application {
    public static void main(String[] args) {
        //Object>String
        //Object>Person>Teachar
        //Object>Person>Student
        Object object = new Student();
        System.out.println(object instanceof Student); //true
        System.out.println(object instanceof Person);  //true
        System.out.println(object instanceof Object);  //true
        System.out.println(object instanceof Teachar);  //False
        System.out.println(object instanceof String);  //False
        System.out.println("=============================");
        Person person = new Student();
        System.out.println(person instanceof Student); //true
        System.out.println(person instanceof Person);  //true
        System.out.println(person instanceof Object);  //true
        System.out.println(person instanceof Teachar);  //False
        // System.out.println(person instanceof String);   编译报错;Person与String同级
        System.out.println("=============================");
        Student student = new Student();
        System.out.println(student instanceof Student); //true
        System.out.println(student instanceof Person);  //true
        System.out.println(student instanceof Object);  //true
        //System.out.println(student instanceof Teachar);  //False  编译报错;Student与Teachar同级
        //System.out.println(student instanceof String);  //False
    }
}

System.out.println(x(对象) instanceof Y(类));

解释X与Y之间是否存在关系,存在关系则编译通过!!!

类型之间的转换

基本类型转换 父 子

父类Person;子类Student;子类Teacher;

子类Teacher;

package com.oop.Demo05;

public class Student extends Person{
    public void go(){
        System.out.println("go");
         }

}

测试类

package com.oop.Demo05;

public class Application {
    public static void main(String[] args) {
        //基本类型转换  父   子
        //子类转换为父类,可能丢失自己本来的一些方法!
        // Object>Person>Teachar  //高到底
        // Object>Person>Student
        Person obj = new Student();
        //Person类型里obj这个对象转换为Student类型,我们就可以使用Student类型的方法了。
        Student student = (Student) obj;  //强制转换将Person类型转换为Student类型了
        ((Student) obj).go();

    }
}

类型转换

  1. 前提把父类引用指向子类的对象
  2. 把子类转换为父类,向上转型
  3. 把父类转换为子类,向下转型,强制转换,可能会丢失一些方法
  4. 方便方法的调用,减少重复的代码!简洁

抽象的 封装、继承、多态!抽象类

你可能感兴趣的:(学习博客,java)