Java instanceof和类型转换 -16天 学习笔记

Instanceof

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

可以帮助我们判断两个类是否有继承关系

如果是父子关系就为true、 如果是兄弟同级关系就会返会false 没有关系会编译出错

//Object > String
        //Object > Person1 > Teacher
        //Objiec > Person1 >Student1

        Object object = new Stunden1();

        //System.out.println(X instanceof Y);//判断是否编译通过

        System.out.println(object instanceof Stunden1);//ture
        System.out.println(object instanceof Person1);//ture
        System.out.println(object instanceof Object);//ture
        System.out.println(object instanceof Teacher);//false
        // Object > Person1 > Teacher 没有在Student1里面所有false,兄弟不能跟父子一样
        System.out.println(object instanceof String);//false
        //Object > String    String跟Person1属于同类也不知Student1里面

        Person1 person = new Stunden1();
        System.out.println("================================");

        System.out.println(person instanceof Stunden1);//ture
        System.out.println(person instanceof Person1);//ture
        System.out.println(person instanceof Object);//ture
        System.out.println(person instanceof Teacher);//false
       // System.out.println(person1 instanceof String);//编译报错

        Stunden1 stunden1 = new Stunden1();
        System.out.println("================================");

        System.out.println(stunden1 instanceof Stunden1);//ture
        System.out.println(stunden1 instanceof Person1);//ture
        System.out.println(stunden1 instanceof Object);//ture
        //System.out.println(stunden1 instanceof Teacher);//编译报错
       // System.out.println(stunden1 instanceof String);//编译报错

类型之间的转换

基本类型的转换 高到低 128 > 64 >32 高转低需要 强转,

同理父子关系 也是需要强转。

1.父类引用指向子类的对象
2.把子类转换为父类,向上转型,自动转型,丢失子类中原本可以之间调用的特有方法
3.父类转换为子类要强制转换,向下转型,丢失父类被子类所重写的方法。
4.方便方法的调用,减少重复的代码

抽象 : 封装,继承,多态
package com.oop;

import com.oop.Demo05.Person1;
import com.oop.Demo05.Stunden1;

//一个项目应该只有一个main方法
public class Application {

    public static void main(String[] args) {
        //类型之间的转换   父亲     儿子

        //向上转型 自动转型 ,又叫多态                  
       Person1 s1 = new Stunden1();
        

       //s1将这个对象转换为Student类型,我们就可以使用Student1类型的方法
        
        ((Stunden1)s1).go(); //强制转换

        //子类转成父类会丢失一些方法
        Stunden1 s2 = new Stunden1();//可以调用本身的方法
        s2.go();;
        // 低转高,自动转换
        
        
    }
    /*
    1.父类引用指向子类的对象
    2.把子类转换为父类,向上转型,自动转型,丢失子类中原本可以之间调用的特有方法
    3.父类转换为子类要强制转换,向下转型,丢失父类被子类所重写的方法。
    4.方便方法的调用,减少重复的代码
    
    抽象 : 封装,继承,多态
    

           */
}
public class Person1 {


}
package com.oop.Demo05;

public class Stunden1 extends Person1 {

    public void go(){
        System.out.println("go");
    }
}

Techer

package com.oop.Demo05;

public class Teacher extends Person1 {

}

猜你喜欢

转载自blog.csdn.net/yibai_/article/details/114903119