이론

암시적, 명시적 관계

박성우기 2015. 9. 18. 17:38
반응형


public class ParentC {


public String nation;

public int studentNo;


public ParentC(String nation) {

this.nation = nation;

System.out.println("ParentC(String nation) call");

}


}




public class ChildT extends ParentC {

private int studentNo;


public ChildT(String name, int studentNo) {
this.nation = name;
// super(name);
this.studentNo = studentNo;
}

}




이렇게 돌리면 this.nation = name 이라는 값이 명시적으로 선언되지 않아서


암시적으로는 ParentC를 상속받았기 때문에 우리는 String nation이라는 값을 상속받았다는 것을 알고 있지만


JAVA에서는 명시적으로 확실히 선언하지 않으면 에러가 발생한다.






public class ParentC {


public String nation;

public int studentNo;


public ParentC(String nation) {

this.nation = nation;

System.out.println("ParentC(String nation) call");

}


}




public class ChildT extends ParentC {

private int studentNo;


public ChildT(String name, int studentNo) {
// this.nation = name;
super(name);
this.studentNo = studentNo;
}

}


그래서 이렇게 명시적으로 super(name)이라고 언급을 해야 오류없이 제대로 작동한다.


이렇게 안하고 ParentC 클래스에 기본 생성자인


public ParentC() { }

를 생성해도 괜찮다.


이 방법 또한 명시적으로 기본생성자를 생성한 것이기 때문에


전에 올린 글에서 가급적이면 모든 경우의 상황을 대비하여 


기본생성자를 오버로딩(중복 메소드) 하라고 했던 것이다.






반응형