public interface Vehicle {
void drive();
}
// 기존 클래스
public class Car implements Vehicle {
@Override
public void drive() {
System.out.println("자동차가 주행합니다.");
}
}
public interface Vehicle {
void drive();
void honk(); // 새로운 메서드 추가
}
public interface Vehicle {
void drive();
// 새로운 기능을 default method로 추가
default void honk() {
System.out.println("경적을 울립니다!");
}
}
public class Car implements Vehicle {
@Override
public void drive() {
System.out.println("자동차가 주행합니다.");
}
}
public class Main {
public static void main(String[] args) {
Vehicle car = new Car();
car.drive(); // "자동차가 주행합니다."
car.honk(); // "경적을 울립니다!" (default method 실행)
}
}
public interface Printer {
void print();
// 새로운 기능 추가
default void scan() {
System.out.println("스캔 기능을 실행합니다.");
}
}
// 기존 클래스
public class BasicPrinter implements Printer {
@Override
public void print() {
System.out.println("문서를 인쇄합니다.");
}
}
public class Main {
public static void main(String[] args) {
Printer printer = new BasicPrinter();
printer.print(); // "문서를 인쇄합니다."
printer.scan(); // "스캔 기능을 실행합니다." (자동 추가된 기능)
}
}
public interface SecureStorage {
void storeData(String data);
// 기본적으로 모든 저장소에서 데이터를 암호화한다고 가정
default void encryptData(String data) {
System.out.println("데이터를 암호화하여 저장합니다.");
}
}
// 기존 클래스 (암호화 필요 없음)
public class SimpleStorage implements SecureStorage {
@Override
public void storeData(String data) {
System.out.println("데이터를 암호화 없이 저장합니다.");
}
}
public class Main {
public static void main(String[] args) {
SecureStorage storage = new SimpleStorage();
storage.storeData("비밀번호123"); // "데이터를 암호화 없이 저장합니다."
storage.encryptData("비밀번호123"); // "데이터를 암호화하여 저장합니다." (기존 원칙과 충돌)
}
}
import java.util.*;
public class SynchronizedCollectionExample {
public static void main(String[] args) {
// 동기화된 컬렉션 생성
Collection<Integer> syncNumbers = Collections.synchronizedCollection(
new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5))
);
// 여러 스레드가 동시에 removeIf 실행 시 충돌 가능성 있음
syncNumbers.removeIf(n -> n % 2 == 0);
System.out.println(syncNumbers); // [1, 3, 5]
}
}
import java.util.*;
public class RemoveIfExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
// 짝수만 제거
numbers.removeIf(n -> n % 2 == 0);
System.out.println(numbers); // [1, 3, 5]
}
}
import java.util.*;
public class SynchronizedCollectionExample {
public static void main(String[] args) {
Collection<Integer> syncNumbers = Collections.synchronizedCollection(
new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5))
);
syncNumbers.removeIf(n -> n % 2 == 0);
System.out.println(syncNumbers); // [1, 3, 5]
}
}
@Override
public boolean removeIf(Predicate<? super E> filter) {
synchronized (this) { // 동기화 적용
return super.removeIf(filter);
}
}