추상클래스(abstract class)란?
추상클래스는 추상메소드를 선언할 수 있는 클래스를 의미한다. 또한 일반적인 클래스와 다르게 상속받는 클래스(자식 클래스)없이 그 자체로 인스턴스를 생성할 수 없다.
추상메소드는
설계만 되어 있고 (메소드의 기본구조인 return type, 메소드 이름, parameter를 선언함),
구현체가 없는 메소드 (중괄호 안의 블럭은 선언하지 않으며, 자식 클래스에서 모두 구현함) 이다.
예제코드
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}
추상클래스의 특징 정리
- 객체를 클래스 그 자체로 생성할 수 없다.
- extends 키워드를 통해 상속하므로, 다중 상속이 불가능하다.
- 추상메소드에 대해서는 자식(상속받은) 클래스에서 반드시 구현해야 한다.
'Java' 카테고리의 다른 글
자바 - 2차원 배열 정렬 (오름차순, 내림차순, 다중 조건) (0) | 2023.03.15 |
---|---|
자바 - 날짜와 시간 (0) | 2023.02.20 |
자바 - 객체지향퀴즈 (0) | 2023.02.20 |
자바 - 인터페이스 (0) | 2023.02.20 |
자바 - 접근 제어자 (0) | 2023.02.20 |
댓글