メインコンテンツまでスキップ

Java Sealed

· 約2分
Mikyan
白い柴犬

After Java 8, the interface of java have become more and more powerful.

  • (Java 8) Default methods Provide optional functionality to all implementations
  • (Java 8) Static methods Utility methods that belong to the interface contract itself, CANNOT be overridden. utility functions that don't need instance context
  • (Java 9) Private methods: keeping internal helper logic hidden from implementers
  • Constants: Shared Contract Values public static final cannot be overriden
  • (Java 17) Sealed: Sealed means you can control exactly which classes can implement your interface (or extend your class). closed hierarchy, This enables better pattern matching, safer APIs, and clearer domain modeling!
  • (Java 8) @FunctionalInterface indicate this interface supports lambda.

Example:

public interface PaymentProcessor {
// Abstract method - must be implemented
void processPayment(double amount);

// Default method - optional to override
default void logTransaction(double amount) {
System.out.println("Processing payment of: $" + amount);
// Common logging logic here
}

// Another default method
default boolean validateAmount(double amount) {
return amount > 0 && amount < 10000;
}
}
public abstract class AbstractPaymentProcessor {
private int defaultAmount = 500;
// Abstract method - must be implemented
void processPayment(double amount);

// Default method - optional to override
void logTransaction(double amount) {
System.out.println("Processing payment of: $" + amount);
// Common logging logic here
}

// Another default method
boolean validateAmount(double amount) {
return amount > 0 && amount < 10000;
}
}