Downcasting with instanceof Operator

后端 未结 2 1134
遇见更好的自我
遇见更好的自我 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.

    0 讨论(0)
  • 2021-01-24 03:13

    Here is how you can use the instanceof operator:

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

    The instanceof operator takes an object on the left hand side and checks if it is an instance of the right hand side argument which is a class.

    obj instanceof Claz
    

    This returns true if the class of obj is an instance of Claz.

    On a side note, I also do highly recommend that you follow Java naming conventions. Instead of naming your class bread4, name it Bread4.

    Classes should start with upper case letters whereas variables and methods should start with lower case letters.

    0 讨论(0)
提交回复
热议问题