this()메소드는 같은 클라스의 다른 생성자를 호출할 때 사용된다면,
super()메소드는 부모 클라스의 생성자를 호출할 떄 사용된다.
public class PracticeSuper {
public static void main(String[] args){
Child ch = new Child();
ch.display();
}
}
class Parent{
int a ;
Parent(){
a = 10;
}
Parent(int n){
a = n;
}
}
class Child extends Parent{
int b;
Child(){
super();
this.b = 20;
}
public void display(){
System.out.println(a);
System.out.println(b);
}
}
여기서 부모 클라스에 생성자를 두개 넣어주는데, 하나는 파라메터 값이 없을 떄 호출하는 생성자이고, 다른 하나는 파라메터 값이 있을 때 호출되는 생성자이다.
만약에 super(30)으로 만들면 , Parent(int n) { a = n} 이 작동해서 30 이랑 20이 출력된다 .
super()메소드는 생성자에 넣어 준다.
'Java' 카테고리의 다른 글
두 변수의 값 바꾸기 (swap) (0) | 2022.01.07 |
---|---|
Try-catch 예외처리 (0) | 2022.01.07 |
super 키워드 (0) | 2022.01.07 |
this참조 변수와 this()메소드 (0) | 2022.01.07 |
i++랑 ++i의 차이점 (0) | 2022.01.07 |
댓글