Using instanceof in if statement

79 views Asked by At
if(objectName instanceof Mammal currentMammal){
    currentMammal.shedHair();

if the (objectName instanceof Mammal) is true then currentMammal is casted to Mammal. I see this works, but dont know how. I have never seen this stuff going on in "if" statements

I believe this makes sense.

if (ao instanceof Mammal) {
    Mammal currentMammal = (Mammal) ao;
    currentMammal.shedHair();
}

but this first snippet is over my head

2

There are 2 answers

1
Z H.KHAN On
0
ltjnbcwx On

The first one is just a syntactic sugar. Actually it do the Mammal currentMammal = (Mammal) ao; for you.