DEV Community

levi
levi

Posted on

Day-7: InstanceOf and access modifiers: JAVA

πŸ” 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

  1. Type Check: Checks if an object is of a given type.
  2. Returns Boolean: Returns true if the object is of the specified type or a subtype.
  3. Interfaces: Works with interfaces and superinterfaces.
  4. Object Type Matters: Evaluates based on the actual object, not the declared variable type.
  5. Superclass Match: Returns true if object is an instance of a superclass in the hierarchy.
  6. Null Always False: instanceof always returns false when the object is null.
  7. Compile-Time Safety: If the compiler knows the check is impossible (e.g., String instanceof Integer), it gives a compile error.
  8. Safe Downcasting: Often used to check type before downcasting to avoid ClassCastException.
  9. 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);
}
Enter fullscreen mode Exit fullscreen mode

TRICKY QUESTION

  1. whats null instanceof null? Compile time error.instanceof requires the right-hand side to be a class or interface type.:
  2. Can we check enum instanceof?
enum Color { RED, GREEN }
Color c = Color.RED;
System.out.println(c instanceof Color);
Enter fullscreen mode Exit fullscreen mode

Yes,enums are classes and extend java.lang.Enum, so instanceof works with them.

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

  1. private: can only be accessed within same class not even in the subclasses. denoted by **private **keyword.
  2. package-private: denoted by no keyword. this give visibility of entity through out same package.
  3. protected : similar to package-private but its subclasses can also access protected entities. use **protected **keyword
  4. public: can be accessed everywhere. use **public **keyword.

Top comments (0)