Java 문법 : Abstract Class

김선미·2022년 6월 14일

추상 클래스(abstract class)

  • 일반적인 클래스와 달리 자신에 대한 인스턴스 생성이 불가능하며 자손 클래스에 대한 인스턴스 생성만 가능하다.
  • 추상 메소드 : 설계만 되어있고 구현체는 없는 상태의 메소드이다.
  • 메소드 이름, 파라미터, 반환 타입 등은 선언 되어 있지만 중괄호 내의 구현체는 비어있다. 중괄호 내의 구현체는 자손 클래스에서 구현해야 한다.
abstract class Bird {
    //추상 클래스 선언
    private int x,y,z;

    void fly(int x, int y, int z){
        printLocation();
        System.out.println("이동합니다.");
        this.x = x;
        this.y = y;
        if(flyable(z)){ //추상 메소드 구현
            this.z = z;
        } else {
            System.out.println("그 높이로는 날 수 없습니다.");
        }
        this.z = z;
        printLocation();
    }

    abstract boolean flyable(int z); // 추상 메소드 선언, 중괄호 사용 불가

    public void printLocation(){
        System.out.println("현재위치 " +x +", "+y+", "+z+"}");
    }
}

class Pigeon extends Bird {
    // 추상 클래스인 Bird를 상속한 자손 클래스가 되기 위해서는 오버라이드를 사용해 추상 메소드인 flyable을 구현해야 함
    @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.fly(1,1,3);
        System.out.println("---공작새---");
        peacock.fly(1,1,3);
        System.out.println("---비둘기---");
        pigeon.fly(3,3,30000);
    }
}
profile
백엔드 개발 공부

0개의 댓글