class Parent {
void greet() {
System.out.println("👋 Hello from Parent");
}
void talk(String msg) {
System.out.println("💬 Parent says: " + msg);
}
}
class Child extends Parent {
@Override
void greet() {
System.out.println("👋 Hello from Child");
}
// 오버로딩된 메서드
void talk(int count) {
System.out.println("💬 Child talks " + count + " times");
}
}
public class Main {
public static void main(String[] args) {
Parent p = new Child(); // p는 Parent 타입 참조
Child c = new Child(); // c는 Child 타입 참조
// 오버라이딩 → 동적 바인딩, 실제 객체 타입(Child)에 따라 메서드 결정
p.greet(); // Child의 greet()
c.greet(); // Child의 greet()
// 오버로딩 → 정적 바인딩, 참조 변수 타입(Parent, Child)에 따라 메서드 결정
p.talk("Hi"); // Parent의 talk(String)
// p.talk(3); // 컴파일 오류! Parent 타입엔 talk(int) 없음
c.talk("Hello"); // Parent의 talk(String)
c.talk(3); // Child의 talk(int)
}
}
public class CollectionClassifier {
// 다중정의된 메서드들
public static String classify(Set<?> s) {
return "집합";
}
public static String classify(List<?> l) {
return "리스트";
}
public static String classify(Collection<?> c) {
return "그 외";
}
public static void main(String[] args) {
Collection<?>[] collections = {
new HashSet<String>(),
new ArrayList<BigInteger>(),
new HashMap<String, String>().values()
};
for (Collection<?> c : collections)
System.out.println(classify(c)); // 결과는?
}
}
public class ListRemoveExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
int num1 = 1;
Integer num2 = 1;
// 다음 두 remove는 다르게 동작
numbers.remove(num1); // 인덱스 1의 요소를 제거
numbers.remove(num2); // 값이 1인 요소를 제거
System.out.print(numbers); // 결과는?
}
}
E remove(int index); // 인덱스를 받아 해당 위치의 요소를 제거
boolean remove(Object o); // 객체를 받아 같은 값을 가진 요소 제거
// 다중정의된 메서드
static class Processor {
public static int process(Object obj) { return 1;}
public static int process(String s) { return 2; }
}
// 호출 예시
Function<String, Integer> func = Processor::process; // 어떤 메서드가 참조될까?
System.out.println(func.apply("hello")); // 몇이 출력될까요?
public static String classifyBetter(Collection<?> c) {
if (c instanceof Set)
return "집합";
else if (c instanceof List)
return "리스트";
else
return "그 외";
}
// 메서드 이름으로 구분하는 예
public class ObjectStreamMethods {
// 다중정의 대신 이름으로 구분
public void writeBoolean(boolean b) { /* ... */ }
public void writeInt(int i) { /* ... */ }
public void writeLong(long l) { /* ... */ }
}