자바 공부/[자바] 기본 공부
[자바 공부 3일차] super와 생성자
햅2024
2024. 11. 8. 20:07
super()는 자식 생성자에서 부모생성자를 호출시키는 함수이다.
그러나 자식 클래스 생성자를 사용할 때, 자동으로 부모 생성자도 호출이 된다.
그럼 왜 super라는 호출 함수를 알아야 하는 것일까?
그건 다음과 같은 이유 때문이다.
public class ex_Parent {
public ex_Parent(String str)
{
System.out.println(str + "부모생성자 입니당");
}
public int Sum (int a, int b)
{
int result = 0;
result = a+b;
return result;
}
}
위 부모 클래스를 보면 생성자에 문자열 변수를 갖고 있다.
public class ex_Child extends ex_Parent {
public ex_Child()
{
System.out.println("기본 생성자 입니다");
}
public void Cal()
{
int a = 10;
int b = 12;
System.out.printf("%d", Sum(a, b));
}
}
그러나 자식 함수의 생성자는 문자열 인자를 갖지 않는다.
이럴 경우 오류가 발생하게 된다.
이럴 때 필요한 것이 super() 호출 함수이다.
public ex_Child()
{
super("오류나지 마!! ");
System.out.println("기본 생성자 입니다");
}
위와 같이 super 함수에 대신 문자열을 넣어주어 호출해준다면 오류가 나지 않는다.