Abstract Class, Abstract Method
Abstract Class
-미완성 설계도. 미완성 메서드를 갖고 있는 클래스.
abstract class Player {
abstract void play(int pos);
abstract void stop();
}
-다른 클래스 작성에 도움을 주기 위한 것. 인스턴스 생성 불가.
Player p = new Player();//error
-상속을 통해 추상 메서드를 완성해야 인스턴스 생성가능.
class AudioPlayer extends Player {
void play(int pos) {} // implement abstract method
void stop() {}
}
//by implementing object, do not use abstract in front of child of Player
AudioPlayer ap = new AudioPlayer();//OK.
//add abstract because one is implemented and another is not.
abstract class AbstractPlayer extends Player {
void play(int pos)
//abstract void stop();
}
Abstract Method
-미완성 메서드. 구현부(몸통 {}) 가 없는 메서드.
/* 주석을 통해 어떤 기능을 수행할 목적으로 작성하였는지 설명한다. */
-꼭 필요하지만 자손마다 다르게 구현될 것으로 예상되는 경우
abstract method를 포함하는 abstract class를 상속받는다면 abstract method를 다 구현해주어야만 제어자 abstract를 생략할 수 있다. 일부만 구현한 경우에는 abstract를 붙여줘야한다는 것을 기억하자.
abstract method는 "필수기능이므로 자식으로 하여금 꼭 구현해야한다" 는 의무 같은 성질이 있다.
abstract class Player {
boolean pause;
int currentPos;
Player() {
pause = false;
currentPos = 0;
}
/* 지정된 위치(pos)에서 재생을 시작하는 기능이 수행되도록 작성되어야 한다. */
abstract void play(int pos);
/* 재생을 즉시 멈추는 기능을 수행되도록 작성되어야 한다. */
abstract void stop();
//instance method=> only after creating instance, usable.
void play() {
play(currentPos);//OK. can use abstract method.
}
}
메서드는 선언부만 알면 호출이 가능하므로, 추상메서드도 호출 가능하다.(16)
자식 클래스 생성
상속을 통해 자식 클래스에서 메서드 구현
instance method를 사용할 수 있다.(instance variable, instance method는 객체 생성 후 사용 가능하기 때문!)
Last updated
Was this helpful?