문제
public class Main{
public static class Parent {
public int x(int i) { return i + 2; }
public static String id() { return "P";}
}
public static class Child extends Parent {
public int x(int i) { return i + 3; }
public String x(String s) { return s + "R"; }
public static String id() { return "C"; }
}
public static void main(String[] args) {
Parent ref = new Child();
System.out.println(ref.x(2) + ref.id());
}
}
Parent id() | Child id() | 결과 |
|---|
| static | static | ✅ hiding (정적 바인딩) → ref.id() → "P" |
| non-static | static | ❌ 컴파일 에러 |
| static | non-static | ❌ 컴파일 에러 |
| non-static | non-static | ✅ 오버라이딩 (동적 바인딩) → ref.id() → "C" |
✅ 기본 개념 정리
| 개념 | 설명 |
|---|
| static method | 클래스에 속하며, 오버라이딩이 아니라 hiding(숨김)만 가능 |
| instance method | 객체에 속하며, 동적 바인딩을 통해 오버라이딩 가능 |
| 같은 이름, static 여부 다름 | 자바에서는 허용되지 않음 → 컴파일 에러 발생 |
✅ 코드 예시 및 결과
✅ Case 1: Parent는 static 제거, Child는 static 유지
public class Parent {
public String id() { return "P"; }
}
public class Child extends Parent {
public static String id() { return "C"; }
}
- 🔥 컴파일 에러 발생
- 이유: 동일한 시그니처의 static/non-static 메서드는 자바에서 허용되지 않음
✅ Case 2: Parent는 static 유지, Child는 static 제거
public class Parent {
public static String id() { return "P"; }
}
public class Child extends Parent {
public String id() { return "C"; }
}
- 🔥 컴파일 에러 발생
- 이유: 동일한 시그니처의 static/non-static 메서드는 자바에서 허용되지 않음
✅ Case 3: Parent, Child 모두 static 제거 (모두 인스턴스 메서드)
public class Parent {
public String id() { return "P"; }
}
public class Child extends Parent {
public String id() { return "C"; }
}
Parent ref = new Child();
System.out.println(ref.id());
- ✅ 정상 작동, 동적 바인딩 적용 → 오버라이딩 성공
✅ 정리표
Parent id() | Child id() | 결과 |
|---|
| static | static | ✅ hiding → ref.id() → "P" |
| non-static | static | ❌ 컴파일 에러 |
| static | non-static | ❌ 컴파일 에러 |
| non-static | non-static | ✅ 오버라이딩 → ref.id() → "C" |
✅ 추가 개념 요약
- hiding: 정적 메서드는 "오버라이딩"이 아닌 "숨김(hiding)"으로 처리됨
- 동적 바인딩: 인스턴스 메서드는 실제 객체 타입 기준으로 메서드 호출 결정됨
- 정적 바인딩: static 메서드는 컴파일 시점에 클래스 타입 기준으로 결정됨
🔍 실무 팁
- static 메서드를 상속/오버라이딩처럼 쓰지 말 것
- 혼용 시 혼란을 막기 위해 명확히 static 또는 인스턴스 방식만 사용할 것