Object 클래스
:모든 클래스의 조상
- 부모 없는 클래스 자동적 Object 클래스 상속받음
- 모든 클래스는 Object 클래스에 정의된 11개의 메서드(toString(),equals()..등등) 상속받음.
class Test{ //→ class Test extends Object 컴파일러 자동추가
}
super
:객체 자신을 가르키는 참조변수 (≒ this)
- 조상멤버와 자신멤버 구별할 때 사용
- 인스턴스 멤버내에만 존재
public class Parent {
int x = 10;
}
public class Child extends Parent{
int x = 20;
public void play(){
System.out.println(x); //20 ,가까운 쪽
System.out.println(this.x); //20
System.out.println(super.x); //10
}
}
public class Test {
public static void main(String[] args) {
Child child = new Child();
child.play();
}
}
super()
:조상의 생성자
- 조상 생성자를 호출할 때 사용
- 조상멤버는 조상 생성자 호출해 초기화
자손생성자는 자기선언 멤버만 초기화 해야함.
public class Parent {
int x,y;
public Parent(int x, int y) {
this.x = x;
this.y = y;
}
}
public class Child extends Parent{
int z;
public Child(int x, int y, int z) {
super(x,y); //조상생성자 호출.
this.z = z;
}
}
★ 모든클래스의 생성자 첫 줄에 생성자 this(),super() 호출해야함! (Object 클래스 제외)
그렇지 않으면 컴파일러 자동 super(); 첫줄에 삽입
public class Parent {
int x,y;
public Parent(int x, int y) {
//super(); 자동추가 → Object();호출
this.x = x;
this.y = y;
}
}
public class Child extends Parent{
int z;
public Parent(int x, int y, int z) {
//super(); 자동추가 → Parent();호출 but 없어 에러 발생 → 클래스만들때는 기본생성자 작성해주자
this.x = x;
this.y = y; //super(x,y);로 고쳐야 함
this.z = z;
}
}'Java' 카테고리의 다른 글
| [Java] 다형성(Polymophism), 참조변수 형변환, instanceof연산자 (0) | 2023.12.23 |
|---|---|
| [Java] 제어자, 지정자(modifier), 캡슐화 (0) | 2023.12.23 |
| [Java] 오버라이딩(OverRiding) (0) | 2023.12.20 |
| [Java] 상속(Inheritance), 포함(composite) (0) | 2023.12.20 |
| [Java] 변수 초기화(명시적, 생성자, 초기화블럭) (0) | 2023.12.18 |