도구
로그인
한국어

코드 배우기자바

자바 추상화

자바 17 기준isBlank·strip · 자바 11 부터

자바 interface 와 abstract class 를 알림 보내기 예제와 비교표로 봐요.

한 줄 뜻

무엇을 해야 하는지만 정해 두고 어떻게 할지는 나중 클래스에 맡기는 방법이에요. 자바에서는 interface 와 abstract class 로 해요.

왜 필요한가

메일·문자 알림 코드를 채널마다 따로 쓰면 빈 글 거르기, 앞뒤 빈칸 지우기, 보낸 횟수 기록 같은 순서를 채널마다 되풀이해요. 한 채널에서 검사를 빼먹으면 그 채널만 빈 알림이 나가요.

Notifier 인터페이스는 "보낼 수 있다"는 약속만 하고, BaseNotifier 는 같은 순서를 한 번만 적어요. 채널 클래스는 보내는 일을 맡은 deliver 하나만 채우면 돼요.

일상 비유

콘센트 모양은 나라마다 정해져 있어요. 전기 제품을 만드는 회사는 그 모양(인터페이스)만 맞추면 되고, 속에서 전기를 어떻게 사용할지는 회사마다 달라요. 추상 클래스는 "전원부는 이미 달려 있으니 기능 부분만 만들어 붙이세요" 하고 건네는 반제품이에요.

예제 코드

Main.java · 55줄
import java.util.ArrayList;import java.util.List; interface Notifier {    boolean send(String to, String message);} abstract class BaseNotifier implements Notifier {    private int sent;     @Override    public final boolean send(String to, String message) {        if (message.isBlank()) {            return false;        }        deliver(to, message.strip());        sent++;        return true;    }     int sentCount() {        return sent;    }     protected abstract void deliver(String to, String text);} class EmailNotifier extends BaseNotifier {    @Override    protected void deliver(String to, String text) {        System.out.println("[email] " + to + " <- " + text);    }} class SmsNotifier extends BaseNotifier {    @Override    protected void deliver(String to, String text) {        String cut = text.length() > 20 ? text.substring(0, 20) + "..." : text;        System.out.println("[sms] " + to + " <- " + cut);    }} public class Main {    public static void main(String[] args) {        EmailNotifier email = new EmailNotifier();        List<Notifier> channels = new ArrayList<>();        channels.add(email);        channels.add(new SmsNotifier());        for (Notifier n : channels) {            n.send("mina", "  Your order has shipped today  ");            n.send("mina", "   ");        }        System.out.println("email sent: " + email.sentCount());    }}

interface 와 abstract class 비교

interfaceabstract class
new 로 만들기XX
객체마다 다른 필드XO
몸통 있는 메서드default·static 만O
생성자XO
한 클래스가 이어받는 수여러 개 implements하나만 extends

인터페이스에 적은 필드는 모두 public static final 상수가 돼요.

언제 사용하나

  • 구현이 여럿 생길 일을 이름으로 먼저 정할 때(저장소, 결제, 알림, 파일 읽기) → interface
  • 자식들이 같은 순서·같은 필드를 나누고 한두 단계만 다를 때 → abstract class
  • 시험할 때 가짜 구현으로 바꿔 끼우고 싶을 때 → interface

클래스는 부모 클래스를 하나만 두지만 인터페이스는 여러 개 implements 할 수 있어요. 망설여지면 인터페이스부터 만들어요.

isBlank, strip 은 자바 11 부터 있는 문자열 메서드예요.

자주 하는 실수

추상 클래스를 new 로 만듦

BaseNotifier 에는 deliver 몸통이 없어서 이 클래스로는 객체를 만들 수 없어요. 추상 메서드를 모두 채운 자식 클래스로 만들어요.

틀린 코드

public class Main {    public static void main(String[] args) {        Notifier n = new BaseNotifier();    }}

javac 가 내는 오류error: BaseNotifier is abstract; cannot be instantiated

고친 코드

public class Main {    public static void main(String[] args) {        Notifier n = new EmailNotifier();        n.send("mina", "hello");    }}

실행하면[email] mina <- hello

추상 메서드를 다른 이름으로 채움

push 를 만들었지만 부모가 요구한 것은 deliver 예요. 이름과 매개변수를 똑같이 맞추고 @Override 를 붙여요.

틀린 코드

class PushNotifier extends BaseNotifier {    protected void push(String to, String text) {        System.out.println("[push] " + to + " <- " + text);    }}

javac 가 내는 오류error: PushNotifier is not abstract and does not override abstract method deliver(String,String) in BaseNotifier

고친 코드

class PushNotifier extends BaseNotifier {    @Override    protected void deliver(String to, String text) {        System.out.println("[push] " + to + " <- " + text);    }}

인터페이스에 바뀌는 값을 두려 함

인터페이스의 필드는 저절로 static final 상수가 돼서 바꿀 수 없어요. 객체마다 다른 값은 추상 클래스(또는 구현 클래스)의 private 필드로 둬요.

틀린 코드

interface Notifier {    int sent = 0;     default void countUp() {        sent++;    }}

javac 가 내는 오류error: cannot assign a value to final variable sent

고친 코드

interface Notifier {    boolean send(String to, String message);} abstract class BaseNotifier implements Notifier {    private int sent;     protected void countUp() {        sent++;    }}

확인 문제

문제 1

객체마다 다른 값을 담는 필드를 두고 자식에게 물려줄 수 있는 쪽은?

답과 까닭 보기

답: 2. abstract class 인터페이스에 적은 필드는 모두 public static final 상수예요. 객체마다 다른 값은 추상 클래스에 둬요.

문제 2

예제의 클래스로 이 코드를 돌리면 무엇이 찍힐까요?

public class Main {    public static void main(String[] args) {        Notifier n = new SmsNotifier();        System.out.println(n.send("joon", " "));    }}

답과 까닭 보기

답: 2. false send 는 final 이라 문자 채널에서도 빈 글 검사를 먼저 해요. 빈칸 하나는 isBlank() 가 true 라 false 만 찍혀요.

자주 묻는 것

인터페이스와 추상 클래스 중 무엇을 먼저 사용하나요?

해야 할 일만 정할 때는 인터페이스부터 사용해요. 여러 구현이 같은 순서나 필드를 나눠 사용해야 하면 그때 추상 클래스를 더해요.

인터페이스에도 몸통 있는 메서드를 둘 수 있나요?

자바 8 부터 default 메서드와 static 메서드를 둘 수 있어요. 다만 객체마다 다른 필드는 둘 수 없어요.

추상 클래스로 객체를 만들 수 있나요?

new 로는 못 만들어요. 추상 메서드를 모두 채운 자식 클래스로 만들어요.