π What is instanceof
?
The instanceof
operator checks whether an object is an instance of a specific class, subclass, or interface. It returns a boolean result.
π Summary of Key Concepts
- Type Check: Checks if an object is of a given type.
-
Returns Boolean: Returns
true
if the object is of the specified type or a subtype. - Interfaces: Works with interfaces and superinterfaces.
- Object Type Matters: Evaluates based on the actual object, not the declared variable type.
-
Superclass Match: Returns
true
if object is an instance of a superclass in the hierarchy. -
Null Always False:
instanceof
always returnsfalse
when the object isnull
. -
Compile-Time Safety: If the compiler knows the check is impossible (e.g.,
String instanceof Integer
), it gives a compile error. -
Safe Downcasting: Often used to check type before downcasting to avoid
ClassCastException
. -
Pattern Matching: Allows type check and casting in one step:
if (obj instanceof String s) { System.out.println(s.toUpperCase()); }
10.Short-Circuit Logic: Pattern variable can be used in same condition safely:
if (obj instanceof String s && s.length() > 5) {
System.out.println(s);
}
TRICKY QUESTION
- whats null instanceof null? Compile time error.instanceof requires the right-hand side to be a class or interface type.:
- Can we check enum instanceof?
enum Color { RED, GREEN }
Color c = Color.RED;
System.out.println(c instanceof Color);
Yes,enums are classes and extend java.lang.Enum, so instanceof works with them.
- whats int instanceof Integer? Compile-time error,instanceof cannot be used with primitives.
ACCESS MODIFIER:
Java provide 4 types of access modifiers, class/field/method defined as:
- private: can only be accessed within same class not even in the subclasses. denoted by **private **keyword.
- package-private: denoted by no keyword. this give visibility of entity through out same package.
- protected : similar to package-private but its subclasses can also access protected entities. use **protected **keyword
- public: can be accessed everywhere. use **public **keyword.
Top comments (0)