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
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.