1 답변
-
네 추상클래스도 생성자를 가질수 있습니다 .
abstract class Product { int multiplyBy; public Product( int multiplyBy ) { this.multiplyBy = multiplyBy; } public int mutiply(int val) { return multiplyBy * val; } } class TimesTwo extends Product { public TimesTwo() { super(2); } } class TimesWhat extends Product { public TimesWhat(int what) { super(what); } }
상위 클래스인 Product는 추상클래스이고 생성자도 있습니다. 그리고 Product를 상속받는 TimesTwo 클래스는 생성자를 가졌는데 여기서 super(2); 호출합니다. 그럼 상속받은 Product의 생성자로 넘어가서 multiplyBy에 2를 대입해줍니다. 마찬가지로 Product를 상속받은 TimesWhat에서도 생성자에서 상위클래스의 생성자를 호출하는데 똑같이 Product의 생성자에 what을 전달해 multiplyBy는 what으로 초기화됩니다.
보통 추상클래스의 생성자는 클래스에 필요한 어떤 제약을 줄 때 사용합니다.
댓글 입력