0
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

Z H.KHAN
  • 7
  • 1
  • 2
  • 5
    This was added in Java 14: https://openjdk.org/jeps/305 – VGR Aug 22 '23 at 02:52
  • 3
    https://docs.oracle.com/en/java/javase/17/language/pattern-matching-instanceof-operator.html the compiler effectively translates your first snippet into your second (the first is sugar for the second). – Levi Ramsey Aug 22 '23 at 02:53
  • 1
    Does this answer your question? [Why is an identifier required for instanceof pattern matching?](https://stackoverflow.com/questions/72446857/why-is-an-identifier-required-for-instanceof-pattern-matching) Also https://stackoverflow.com/questions/61939967/pattern-matching-instanceof – knittl Aug 22 '23 at 06:35

2 Answers2

2

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

ltjnbcwx
  • 21
  • 4
-2

Got the answer. https://docs.oracle.com/en/java/javase/17/language/pattern-matching-instanceof-operator.html#GUID-843060B5-240C-4F47-A7B0-95C42E5B08A7.

This is a new feature added in JDK 16.

Z H.KHAN
  • 7
  • 1
  • 2
  • 2
    I think the downvote/not upvoting happened because of .missing explanation. Also leaves a better impression leaving out "ChatGPT" and emoji. Just a tip. Nice reading of references – Joop Eggen Aug 22 '23 at 04:26