Downcasting with instanceof Operator

后端 未结 2 1133
遇见更好的自我
遇见更好的自我 2021-01-24 02:45

Downcasting is when child class refers to the object of Parent class. I tried doing it without the instanceof operator.

class Food { }  
class bread4 extends Foo         


        
2条回答
  •  不思量自难忘°
    2021-01-24 02:57

    instanceof operator provides runtime type checking. For instance, if you had a class Food and two subtypes, Bread4 and Bread5, then:

    static void method(Food a) {
       Bread4 b = (Bread4) a;
       System.out.println("Downcasting performed"); 
    }
    

    calling this method like:

    Food four = new Bread4();
    Food five = new Bread5();
    Bread4.method(four); //the cast inside is done to Bread4, therefore this would work
    Bread4.method(five); //the object of type Bread5 will be cast to Bread4 -> ClassCastException
    

    To avoid this, you use the instanceof operator

    static void method(Food a) {
       if (a instanceof Bread4) {
           Bread4 b = (Bread4) a;
           System.out.println("Downcasting performed"); 
       }
    }
    

    therefore, in case you call

    Bread4.method(five)
    

    the check return false so no ClassCastException occurs.

    Hope this answers your question.

提交回复
热议问题