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