Java

자바 프로그래밍 (Java) - 26 : 상속 (final과 abstract - 2)

n.han 2016. 7. 13. 15:08

  - 다음은 Person 클래스를 추상화한 것이다. 추상화된 메서드가 없어도 에러가 발생하지 않은 것을 볼 수 있다.

 

  즉 추상 클래스는 꼭 추상 메서드가 있어야하는 것은 아니다. 

 

public abstract class Person {

        private String name;

        Person(String name){

               this.name = name;

        }

       

        public void eat(){

               System.out.println("Eating...");

        }

}

 

 - 또한 부모 클래스의 메서드가 추상화된 경우, 자식 클래스에서 꼭 재정의 해주어야 한다.

 

재정의하지 않으면 컴파일 에러가 발생한다. 

 

public abstract class Person {

        private String name;

        Person(String name){

               this.name = name;

        }

       

        public abstract void eat();

}

public class Student extends Person{

        private int studentID;

        public Student(String name, int studentID){

               // 부모 생성자의 명시적 호출

               super(name);

               this.studentID = studentID;

        }      

}

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

        The type Student must implement the inherited abstract method Person.eat()