Java

자바 프로그래밍 (Java) - 24 : 상속 (오버라이딩)

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

- 오버라이딩 (Overriding)

 

부모로부터 멤버 메서드를 상속 받을 때, 자식 클래스에서 그 메서드를 재정의하는 것을 메서드 오버라이딩이라고 한다.

 

메서드 오버라이딩을 수행하는 경우 메서드의 시그니쳐(반환 형, 매개변수)를 변경하지 않아야 한다.

 

오버라이딩되는 메서드의 접근 제한자는 변경할 수 있는데, 부모의 접근 제한자보다 넓은 범위로만 변경할 수 있다.

 

다만 부모의 메서드를 오버라이딩할 때, 부모의 재정의되는 메서드의 기능이 필요한 경우가 많다.

 

이 부분을 자식 메서드에서 재정의 시 똑같이 작성하면 코드 중복이 발생한다.

 

이런 중복을 super 키워드로 자식에 의해서 가리어진 부모의 멤버를 호출하여 피할 수 있게 된다.

 

 

public class Person {

        private String name;

        Person(String name){

               this.name = name;

        }

       

        public void eat(){

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

        }

}

public class Student extends Person{

        private int studentID;

        public Student(String name, int studentID){

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

               super(name);

               this.studentID = studentID;

        }

       

        // 부모의 eat() 메서드를 Override

        public void eat(){

               System.out.println("Student is");

               super.eat();

        }

}

public class MainClass {

        public static void main(String args[]) {

        Student std1 = new Student("Nuri", 16005699);

        std1.eat();

        }

}

출력 결과

Student is

Eating...