Skip to Content
Suffering builds character

9. 추상 메서드

1. 추상 메서드, Abstract method

이와 같이 Animal 클래스 내 sing()는 구현을 강제하지 않으면서,

Animal 클래스를 확장할 하위 클래스들에 대해서는 각각의 클래스의 특징에 맞게 자유롭게 구현할 수 있도록 제공하기 위해서는 해당 메서드를 추상화 시켜두어야 함

메서드 앞에 abstract 키워드를 추가

Animal.java
public class Animal { public abstract void sing(); }

→ 어떤 메서드 앞에 abstract 키워드를 추가할 경우 해당 메서드는 구현이 강제되지 않게됨

class Animal과 sing() 부분에서 컴파일 에러 발생

Animal.java
public class Animal { // Compile Error. public abstract void sing(); // Compile Error. } // ...
Main.java
public static void main(String[] args) { Animal a = new Animal(); // Error, 인스턴스 생성 불가 a.sing(); // Error, sing()의 동작이 구현되지 않음 }

컴파일 에러 내용

컴파일 에러 메시지
"The type Animal must be an abstract class to define abstract methods" "The abstract method sing in type Animal can only be defined by an abstract class"

→ Animal 타입(class)에 있는 추상 메서드 sing()은 추상 클래스에서만 정의할 수 있음

→ sing() 메서드를 구현하지 않았기 때문에 이대로 Animal 클래스의 인스턴스를 생성하게 될 경우, 생성된 인스턴스로 sing()이 수행할 수 있는 동작이 없기 때문에 객체(인스턴스) 생성이 불가능함

따라서 해당 클래스는 결과적으로 객체를 생성할 수 없는 클래스가 되어버림

Main.java
Animal a = new Animal(); // ERROR. // "The type Animal must be an abstract class to define abstract methods"
Last updated on