The type of the pattern variable must be a subtype of the variable on the left side of the expression. It also cannot be the same type.
While the second line compiles, the last line does not compile because pattern matching requires that the pattern variable type Integer be a strict subtype of Integer.
*** Date: Thursday, April 20, 2023 at 11:57:02 AM Central Daylight Time
*** Platform Details:
*** System properties:
java.runtime.name=Java(TM) SE Runtime Environment
java.runtime.version=17.0.6+9-LTS-190
*** System environment variables:
*** Features:
*** Plug-in Registry:
*** User Preferences:
*** Current Install Configuration:
*** Security Configuration:
Integers again
both integers
this is an object
Simon Roberts wrote:I concur:
\eclipse-workspace\oracle_certified_professional_17\src\ocp_java_17>javac PatternMatching.java
PatternMatching.java:18: error: expression type Integer is a subtype of pattern type Integer
if (i1 instanceof Integer i2) {
^
PatternMatching.java:21: error: expression type Integer is a subtype of pattern type Integer
if (i4 instanceof Integer i2) {
^
PatternMatching.java:24: error: expression type Integer is a subtype of pattern type Object
if (i4 instanceof Object o1) {
^
3 errors
Gouri Kalanidhi wrote:I'm using Java 17 version as I'm preparing for OCP 17 certification. Here's the exact version that eclipse IDE is using, extracted from eclipse installation details:
Enthuware - Best Mock Exams and Questions for Oracle Java Certifications
Quality Guaranteed - Pass or Full Refund!
There are three kinds of actuaries: those who can count, and those who can't.
[OCP 17 book] | [OCP 11 book] | [OCA 8 book] [OCP 8 book] [Practice tests book] [Blog] [JavaRanch FAQ] [How To Ask Questions] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
For my next trick, I'll need the help of a tiny ad ...
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
|