- super() 생성자
모든 클래스의 객체는 생성자 없이는 만들 수 없다.
super() 생성자 : 부모클래스의 생성자 호출. 첫번째 줄애 구현해야 함
super 참조변수 : 부모클래스의 객체를 참조하는 변수
📌
package chap7;
class Super {
int x;
Super() {
this(0);
}
Super(int x) { // Super의 생성자
this.x = x;
}
}
class Child extends Super { // 기본 생성자가 제공됨. <-public Child(){ Super(); } 오류
int y;
public Child() {
super(10);
System.out.println("생성자 호출");
}
}
public class SuperEx1 {
public static void main(String[] args) {
Child c = new Child();
System.out.println(c.x);
System.out.println(c.y);
}
}
- super 생성자
super 참조변수 : 부모클래스의 객체를 참조하는 참조변수
부모객체의 멤버 호출시 사용되는 참조변수다.
super 생성자
1. 부모클래스의 생성자를 자손클래스의 생성자에서 호출
2. 첫줄에서 호출해야 함.
3. 부모클래스의 생성자에 매개변수가 있는 생성자만 있다면 반드시 super()를 호출해야함.
이때 super(매개변수)는 부모클래스의 생성자와 맞아야 한다.
4. 부모클래스의 생성자에 매개변수가 없는 생성자가 있다면 super() 생략할 수 있음.
5. 자손 클래스의 생성자에서부모클래스의 생성자를 호출해야함
📌
package chap7;
class Super2{
int x=10;
void method() {
System.out.println("Super2 클래스의 method()");
}
}
class Child2 extends Super2{
int x = 20;
@Override
void method() {
super.method(); //부모클래스의 method() 호출
System.out.println("Child2 클래스의 method()");
int x=30;
System.out.println("x="+x); //30
System.out.println("this.x="+this.x); //20
System.out.println("super.x="+super.x);//10
}
}
public class SuperEx2 {
public static void main(String[] args) {
Child2 c = new Child2();
c.method();
}
}
'수업(국비지원) > Java' 카테고리의 다른 글
| [Java] chap7 : 클래스의 관계 - Pakage 패키지 예제 (0) | 2023.04.15 |
|---|---|
| [Java] chap7 : 클래스의 관계 - 오버로딩, 오버라이딩 (0) | 2023.04.15 |
| [Java] chap7: 클래스의 관계 - 상속1 (0) | 2023.04.15 |
| [Java] chap6: 클래스와 객체 - 초기화 블럭 (0) | 2023.04.15 |
| [Java] chap6: 클래스와 객체 - This 예약어, This 예약어 Exam6 (0) | 2023.04.15 |