Downcasting with instanceof Operator

后端 未结 2 1136
遇见更好的自我
遇见更好的自我 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条回答
  •  梦毁少年i
    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.

提交回复
热议问题