Skip to content

Commit ae09da7

Browse files
authored
Update complete-java21-qa.md
1 parent 085fbcb commit ae09da7

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

complete-java21-qa.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -570,6 +570,41 @@ ref.field; // Parent's field (hidden - compile time)
570570

571571
---
572572

573+
### Q33: When Java encounters overloaded methods, what determines which method is called at compile-time vs runtime?**
574+
575+
**Answer: Two-Phase Resolution Process**
576+
577+
**Compile-Time (Method Overloading)**
578+
* **What's decided:** Which overloaded method signature to use
579+
* **Based on:** Reference type of the variable (not object type)
580+
* **Rule:** Exact match first, then compatible types (widening/inheritance)
581+
582+
**Runtime (Method Overriding)**
583+
* **What's decided:** Which implementation of the chosen method to execute
584+
* **Based on:** Actual object type (polymorphism)
585+
* **Rule:** Most specific implementation in inheritance hierarchy
586+
587+
```java
588+
interface Person { default void speak() { System.out.println("Person speaking"); } }
589+
class Father implements Person { public void speak() { System.out.println("Father speaking"); } }
590+
class Mother implements Person { public void speak() { System.out.println("Mother speaking"); } }
591+
592+
static void speak(Person p) { System.out.print("Person: "); p.speak(); }
593+
static void speak(Father f) { System.out.print("Father: "); f.speak(); }
594+
595+
public static void main(String[] args) {
596+
Person p = new Father();
597+
Father f = new Father();
598+
Mother m = new Mother();
599+
600+
speak(p); // Compile-time: speak(Person) - Runtime: Father.speak() → "Person: Father speaking"
601+
speak(f); // Compile-time: speak(Father) - Runtime: Father.speak() → "Father: Father speaking"
602+
speak(m); // Compile-time: speak(Person) - Runtime: Mother.speak() → "Person: Mother speaking"
603+
}
604+
```
605+
606+
---
607+
573608
### Q34: When is super() automatically inserted by the compiler?
574609
**Answer:** The compiler inserts `super()` **only if**:
575610
1. Constructor doesn't explicitly call `super()` or `this()`

0 commit comments

Comments
 (0)