본문 바로가기

프로그래밍/JAVA

private 메소드를 하위에서 다시 만들어서 호출 할 때

class Animal{
 private void show()
 {
  System.out.println("animal");
 }
}

class Human extends Animal{
 public void show()
 {
  System.out.println("Human");  
 }
}

class Test {
 public static void main(String args[])  {  
  Animal a = new Human();
  a.show();
 }
}

compile error : show() has private access in Animal

a 객체는 a의 명세를 가지고 메소드를 호출하는 데, a의 명세에서 보면, show는 private이기 때문에
실행 시에는 실제 객체가 생성된 Human show()에 접근하겠지만, 컴파일 시에는 명세만으로 가지고
검사를 하기 떄문에 컴파일 에러가 발생하게 되는 것이다.