25. Advanced Topics (Optional for Intermediate Level)
This chapter is marked as optional for intermediate level, but trust me — these topics are extremely important in real-world Java development (especially in 2026). Many companies ask about them in interviews, and they appear in almost every large-scale project.
We’re going to cover:
- Annotations
- Reflection
- Enums
- Inner classes (static, non-static, anonymous)
- Garbage Collection
- Java Modules (Java 9+)
As always, we’ll go super slowly, with real-life analogies, complete runnable programs, step-by-step explanations, tables, common mistakes, and tons of examples you can copy-paste and run right now.
Let’s dive in — grab your cutting chai! ☕
1. Annotations
Annotations are metadata — extra information attached to classes, methods, fields, etc. They don’t directly affect program execution, but tools/frameworks (like Spring, Hibernate, JUnit) read them and behave differently.
Syntax: Start with @ symbol.
Built-in annotations you use every day:
| Annotation | Purpose | Example Usage |
|---|---|---|
| @Override | Tells compiler: this method overrides a superclass method | @Override public void run() |
| @Deprecated | Marks a method/class as outdated | @Deprecated public void oldMethod() |
| @SuppressWarnings | Tells compiler to ignore specific warnings | @SuppressWarnings(“unchecked”) |
| @FunctionalInterface | Marks an interface as functional (one abstract method) | @FunctionalInterface interface MyFunc {} |
Custom Annotation Example (very common in frameworks)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) // Available at runtime @Target(ElementType.METHOD) // Can be placed on methods public @interface MyLog { String value() default "Info"; // Element with default value int level() default 1; } |
Using it:
|
0 1 2 3 4 5 6 7 8 9 10 11 |
public class MyService { @MyLog(value = "User login", level = 2) public void login(String username) { System.out.println(username + " logged in"); } } |
Reading annotations at runtime (reflection — next topic):
|
0 1 2 3 4 5 6 7 8 9 10 |
Method method = MyService.class.getMethod("login", String.class); MyLog log = method.getAnnotation(MyLog.class); if (log != null) { System.out.println("Log: " + log.value() + ", Level: " + log.level()); } |
2. Reflection
Reflection allows you to inspect and modify classes, methods, fields, etc. at runtime — even private ones!
Use cases:
- Frameworks (Spring, Hibernate) use reflection to auto-configure beans
- JUnit uses it to find @Test methods
- Serialization, dependency injection, dynamic proxies
Important classes:
- Class
- Field
- Method
- Constructor
Example: Inspecting a class at runtime
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
import java.lang.reflect.*; public class ReflectionDemo { public static void main(String[] args) throws Exception { // 1. Get Class object Class<?> clazz = Student.class; // or Class.forName("com.example.Student") // 2. Class info System.out.println("Class name: " + clazz.getName()); System.out.println("Simple name: " + clazz.getSimpleName()); System.out.println("Superclass: " + clazz.getSuperclass()); // 3. Fields (including private) Field[] fields = clazz.getDeclaredFields(); for (Field f : fields) { System.out.println("Field: " + f.getName() + ", Type: " + f.getType()); } // 4. Methods Method[] methods = clazz.getDeclaredMethods(); for (Method m : methods) { System.out.println("Method: " + m.getName()); } // 5. Create instance dynamically Constructor<?> constructor = clazz.getConstructor(String.class, int.class); Object student = constructor.newInstance("Amit", 22); // 6. Call private method Method privateMethod = clazz.getDeclaredMethod("printSecret"); privateMethod.setAccessible(true); // Bypass private privateMethod.invoke(student); // 7. Modify private field Field nameField = clazz.getDeclaredField("name"); nameField.setAccessible(true); nameField.set(student, "Webliance"); System.out.println("New name: " + nameField.get(student)); } } |
Student class for above example:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Student { private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } private void printSecret() { System.out.println("Secret: I love Java!"); } } |
Warning: Reflection is slow and breaks encapsulation — use only when necessary (frameworks, testing, dynamic behavior).
3. Enums
Enums are special classes that represent a fixed set of constants.
Syntax:
|
0 1 2 3 4 5 6 7 8 |
public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } |
Features:
- Type-safe
- Can have fields, methods, constructors
- Can implement interfaces
Advanced Enum Example (with fields & methods)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
public enum TrafficLight { RED("Stop", 30), GREEN("Go", 45), YELLOW("Wait", 5); private final String action; private final int durationSeconds; // Constructor TrafficLight(String action, int durationSeconds) { this.action = action; this.durationSeconds = durationSeconds; } public String getAction() { return action; } public int getDuration() { return durationSeconds; } public static TrafficLight next(TrafficLight current) { return values()[(current.ordinal() + 1) % values().length]; } } |
Usage:
|
0 1 2 3 4 5 6 7 8 9 |
TrafficLight light = TrafficLight.RED; System.out.println(light + ": " + light.getAction() + " for " + light.getDuration() + " seconds"); System.out.println("Next: " + TrafficLight.next(light)); |
4. Inner Classes (Static, Non-static, Anonymous)
Inner classes are classes defined inside another class.
| Type | Syntax / Declaration | Can access outer fields? | Static? | Use Case |
|---|---|---|---|---|
| Non-static (Inner) | class Inner { … } | Yes (even private) | No | Helper class tightly coupled to outer |
| Static Nested | static class StaticNested { … } | Only static fields | Yes | Utility/helper class inside outer |
| Local | Inside method: class Local { … } | Yes (effectively final) | No | Very short-lived helper |
| Anonymous | new SuperClass() { … } or new Interface() { … } | Yes (effectively final) | No | One-time use (listeners, comparators) |
Example: All Types
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
public class Outer { private int outerField = 100; private static int staticField = 200; // 1. Non-static inner class class Inner { void print() { System.out.println("Outer field: " + outerField); // OK } } // 2. Static nested class static class StaticNested { void print() { System.out.println("Static field: " + staticField); // OK // System.out.println(outerField); // ERROR! } } // 3. Method with local & anonymous inner class void demo() { class Local { void show() { System.out.println("Local inner"); } } Local local = new Local(); local.show(); // Anonymous inner class Runnable anon = new Runnable() { @Override public void run() { System.out.println("Anonymous: " + outerField); } }; anon.run(); } public static void main(String[] args) { Outer outer = new Outer(); // Non-static inner Outer.Inner inner = outer.new Inner(); inner.print(); // Static nested Outer.StaticNested nested = new Outer.StaticNested(); nested.print(); outer.demo(); } } |
5. Garbage Collection (GC) – How Java Cleans Memory
Java has automatic memory management — you never manually free memory (no delete like C++).
Garbage Collector (GC) automatically reclaims memory from objects that are no longer reachable.
Key Concepts:
- Heap → where objects live
- Garbage → objects with no live references
- Reachability → object is reachable if there is a path from GC roots (stack variables, static fields, etc.)
Common GC Algorithms (you don’t need to know deeply):
- Serial GC → single thread
- Parallel GC → multiple threads
- G1 GC → default in Java 11+ (region-based, low pause)
- ZGC / Shenandoah → ultra-low pause (Java 15+)
How to help GC:
- Set objects to null when no longer needed
- Use try-with-resources for closeable resources
- Avoid huge object graphs
Example:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class GcDemo { public static void main(String[] args) { Object obj = new byte[10 * 1024 * 1024]; // 10 MB object obj = null; // Now eligible for GC System.gc(); // Suggest GC (not guaranteed!) System.out.println("Object is now eligible for GC"); } } |
6. Java Modules (Java 9+ – Project Jigsaw)
Java 9 introduced the module system — a way to structure large applications with strong encapsulation and explicit dependencies.
module-info.java (the module descriptor)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
// In src/main/java/com/webliance/app/module-info.java module com.webliance.app { requires java.base; // Implicit, but can be explicit requires java.sql; // For JDBC exports com.webliance.app.service; // Public API opens com.webliance.app.internal; // Allow reflection } |
Benefits:
- Strong encapsulation — private packages hidden
- Better security
- Smaller runtime (jlink → custom JRE)
Real-world: Spring Boot 3+ uses modules heavily.
Quick Recap Table (Your Cheat Sheet)
| Topic | Key Takeaway / Best Practice | Example |
|---|---|---|
| Annotations | Metadata for frameworks/compilers | @Override, @MyLog |
| Reflection | Runtime inspection/modification | Class.forName(), getMethod() |
| Enums | Type-safe constants + fields/methods | enum Day { MONDAY } |
| Inner Classes | Nested classes — static, non-static, anonymous | class Inner {} vs static class Nested {} |
| Garbage Collection | Automatic memory cleanup | obj = null; + System.gc() (hint only) |
| Java Modules | Strong encapsulation & dependencies (Java 9+) | module-info.java |
Homework for You (Practice to Master!)
- Annotations Create custom @LogExecutionTime annotation → use reflection to measure method execution time.
- Reflection Write a method that prints all fields and methods of any object passed to it.
- Enums Create enum Level { LOW, MEDIUM, HIGH } with int value() and fromValue(int) methods.
- Inner Classes Create an anonymous Comparator to sort list of strings by length.
- Modules Create two modules: com.webliance.core and com.webliance.app → make app require core.
You’ve completed the entire Core Java journey — congratulations! 🎉 You now know everything from basics to advanced topics — you’re ready for real-world projects, Spring Boot, interviews, and open-source contributions.
What would you like next?
- Deep dive into Spring Boot?
- Advanced topics (Concurrency, JVM internals, Design Patterns)?
- Solve interview questions together?
- Debug any code you wrote?
Just tell me — I’m right here with another cup of cutting chai! ☕🚀
