늦은 프로그래밍 이야기

객체지향 (3) 추상클래스, 인터페이스 본문

내일배움캠프/Java 기초

객체지향 (3) 추상클래스, 인터페이스

한정규 2022. 11. 16. 12:12

추상클래스 (Abstract Class)

 - 상속받는 클래스 없이 단독으로 인스턴스를 생성할 수 없음.

 - 몸체가 없는 메소드를 가질 수 있다. (추상메소드)

 - 일반적인 메소드도 사용가능.

 - 공통 필드와 메소드 통일 목적.

abstract class 클래스명 {
    필드 선언;
    abstract 리턴타입 메소드명(인수목록);
}
abstract class Bird {
    private int x, y, z;
}

추상메소드 (Abstract method)

 - 설계만 되어있고, 수행되는 코드에 대해서는 작성이 안된 메소드

 - 상속받는 클래스 작성자가 작성하도록 하기 위함.

 

형식

abstract 리턴타입 메소드명();
abstract boolean flyable(int z);

 - 중괄호 내의 블럭(몸체)이 존재하지 않음.

 

예시

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("그 높이로는 날 수 없습니다");
        }
        printLocation();
    }

    abstract boolean flyable(int z);  // 추상메소드

    public void printLocation() {
        System.out.println("현재 위치 (" + 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 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);
    }
}

인터페이스 (Interface)

 - 객체의 특정 행동의 특징을 정의

 - 접근제어자, 리턴타입, 메소드명 만 정의한다.

 - 필드를 변경할 수 없고, 메소드의 몸체도 만들 수 없다.

 - 객체를 만들 수 없다.

 - 인터페이스를 구현하는 클래스는 인터페이스의 내용을 반드시 구현해야 한다.

 

 

 

인터페이스 정의

 - 인터페이스의 멤버에는 어떠한 제한자도 붙이지 않는다.

 - 그러나 필드에는 public static final, 메소드에는 abstract 제한자를 붙인 것이나 마찬가지.

 - 따라서 필드는 상수이고, 메소드는 추상메소드이다.

interface 인터페이스명 {
    리턴타입 추상메소드명();
}
interface Bird {
    void fly(int x, int y, int z);
}

 

인터페이스 구현

 - 클래스와 조합하여 사용.

 - 여러 개의 인터페이스를 구현할 수 있음.

class 클래스명 implements 인터페이스명 {
    ...
}

 

예시

interface Bird {
    void fly(int x, int y, int z);     // 인터페이스 정의
}

class Pigeon implements Bird{          // 인터페이스 구현
    private int x,y,z;

    @Override                          // 인터페이스의 메소드를 오버라이딩
    public void fly(int x, int y, int z) {
        printLocation();
        System.out.println("날아갑니다.");
        this.x = x;
        this.y = y;
        this.z = z;
        printLocation();
    }
    public void printLocation() {
        System.out.println("현재 위치 (" + x + ", " + y + ", " + z + ")");
    }
}

public class Main {

    public static void main(String[] args) {
        Bird bird = new Pigeon();
        bird.fly(1, 2, 3);
//        bird.printLocation(); // compile error
    }
}

 - 인터페이스인 Bird 타입으로 선언한 bird 변수는 실제로 Pigeon 객체이지만, 인터페이스인 Bird에 선언되지 않은 printLocation()이라는 함수를 호출할 수 없다.

 - 인터페이스 타입으로 선언되어 있는 부분은 실제 객체가 무엇이든지, 인터페이스에 정의된 행동만 할 수 있다.


Comments