자바 – 추상 클래스

추상 클래스란 무엇입니까?

추상 클래스는 추상 메소드선언할 수 있는 클래스를 의미합니다. 또한 일반 클래스와 달리 상속받은 클래스(자식 클래스) 없이 자신의 인스턴스를 생성할 수 없습니다.

추상 메서드

그냥 디자인 (메서드의 기본 구조를 나타내는 반환 유형, 메서드 이름 및 매개 변수 선언),

구현되지 않은 방법 (중괄호 안의 블록은 선언되지 않고 모두 자식 클래스에서 구현됩니다.)

샘플 코드

abstract class Bird {
    private int x, y, z;

    void fly(int x, int y, int z) {
        printLocation();
        System.out.println("move");
        this.x = x;
        this.y = y;
        if (flyable(z)) {
            this.z = z;
        } else {
            System.out.println("This bird cannot fly at that height.");
        }
        printLocation();
    }

    abstract boolean flyable(int z); // 추상메소드, 메소드 선언 당시 그 내용은 구현하지 않는다.

    public void printLocation() {
        System.out.println("current location {" + x + ", " + y + ", " + z + "}");
    }
}

class Pigeon extends Bird {
    // 추상메소드는 자식 클래스에서 구현한다.
    @Override
    boolean flyable(int z) {
        return z < 10000;
    }
}

class Peacock extends Bird {
    @Override
    boolean flyable(int z) {
        return false;
    }
}

public class Main {
    public static void main(String() args) {
//        Bird bird = new Bird(); // 추상클래스의 인스턴스는 자체적으로 생성할 수 없다.
        Bird pigeon = new Pigeon();
        Bird peacock = new Peacock();
        System.out.println("--- pigeon ---");
        pigeon.fly(1, 1, 3);
        System.out.println("--- peacock ---");
        peacock.fly(1, 1, 3);
        System.out.println("--- pigeon ---");
        pigeon.fly(3, 3, 30000);
    }
}

실행 결과

--- pigeon ---
current location {0, 0, 0}
move
current location {1, 1, 3}
--- peacock ---
current location {0, 0, 0}
move
This bird cannot fly at that height.
current location {1, 1, 0}
--- pigeon ---
current location {1, 1, 3}
move
This bird cannot fly at that height.
current location {3, 3, 3}

추상 클래스의 특징

  • 객체는 클래스 자체에서 만들 수 없습니다.
  • 상속은 extend 키워드를 통해 이루어지기 때문에 다중 상속은 불가능합니다.
  • 추상 메서드는 자식(상속된) 클래스에서 구현되어야 합니다.