Java Interview Prep: Anonymous Classes, Marker Interfaces & Immutable Objects

Headline: Cracking the Core Java Interview: 4 Concepts You Must Know 🔍 1. What is an Anonymous Class? It’s a local class without a name, declared and instantiated in a single expression. Use Cases: Perfect for event listeners in GUI apps (like ActionListener in Swing) or when you need a quick, one-off implementation of an interface/abstract class. 2. What is a Marker Interface? It’s an interface with no methods or fields. It signals metadata to the JVM or compiler. Examples: Serializable (marks class for conversion to byte stream) and Cloneable (marks class as eligible for Object.clone()). 3. How to Create an Immutable Class? Think of String or Wrapper classes. Follow these rules: • Declare the class final (or use private constructors). • Make all fields private and final. • No setter methods. • If holding a mutable object (like Date/Collection), return a defensive copy in the getter. 4. Can Static Methods Be Overridden? No. Static methods are hidden, not overridden. Overriding relies on runtime object type (polymorphism), but static methods are resolved at compile-time based on the reference type. --- Q1: Is the Runnable interface a Marker Interface? (Think about it!) A: No. Runnable declares the run() method, so it is a Functional Interface, not a Marker Interface. Q2: If you have an Immutable class containing a List, how do you protect it in the getter? A: Return Collections.unmodifiableList(this.list) to prevent the caller from adding/removing elements. Q3: In the code Parent p = new Child(); p.staticMethod(); whose static method gets called? A: Parent’s method. The method belongs to the class, not the object. 💬 Which of these concepts trips you up the most? Let me know in the comments! #Java #Programming #CodingInterview #SoftwareEngineering #TechTips #CoreJava

To view or add a comment, sign in

Explore content categories