정리/Java

자바의 정석 73~74강 오버라이딩, 참조변수 super, 생성자 super()

민발자 2023. 8. 5. 05:47
728x90

ch 7-7~9 오버라이딩

1. 오버라이딩

상속받은 조상의 메서드를 자신에 맞게 변경하는것

선언부 변경불가, 구현부만 변경가능

class Point {
	int x;
	int y;
    
	String getLocation(){
		return "x :" + x + "y :" + y;
	}
}

class Point3D extends Point {
	int z;

	// 상속받은 getLocation()을 오버라이딩 
	String getLocation(){
		return "x :" + x + "y :" + y + "z: " + z;
	}
}

 

2. 오버라이딩 조건

  • 선언부가 조상 메서드와 일치(반환타입, 메서드 이름, 매개변수 목록)
  • 접근 제어자를 조상 메서드보다 좁은 범위로 변경 불가 
  • 예외는 조상 메서드보다 많이 선언 불가

 

3. 오버로딩과 오버라이딩

오버로딩 : 이름만 같을 뿐 기존에 없는 새로운 메서드를 정의 new

오버라이딩 : 상속받은 메서드의 내용을 변경 change

class Parent {
	void parentMethod() {}
}

class Child extends Parent {
	void parentMethod() {} // 오버라이딩
	void parentMethod(int i) {} // 오버로딩
    
	void childeMethod() {} // 메서드 정의
	void childeMethod(int i) {} // 오버로딩
	void childeMethod() {} // 중복 정의 에러 발생
}

ch 7-10~11 참조변수 super, 생성자 super()

1. 참조변수 super

객체 자신을 가리키는 참조변수, 인스턴스 매서드(생성자)내에만 존재, static 메서드내에서 사용 불가

조상의 멤버를 자신의 멤버와 구별할 때 사용

this와 유사

// 조상 멤버와 자신 멤버 구별
class Parent{
	int x = 10; // super.x
}

class Child extends Parent {
	int x = 20; // this.x
	void method() {
		System.out.println(this.x); // 20
		System.out.println(super.x); // 10
	}
}

// super와 this 같을 수 있음
class Parent{
	int x = 10; // super.x, this.x 둘 다 해당
}

class Child extends Parent {
	void method() {
		System.out.println(this.x); // 10
		System.out.println(super.x); // 10
	}
}

 

2. super()

조상의 생성자를 호출할 때

상속은 생성자와 초기화블럭 상속 불가

조상의 멤버는 조상의 생성자를 호출하여 초기화

class Point{
	int x, y;
	
	Point(int x, int y){
		this.x = x;
		this.y = y;
    }
}

class Point3D extends Point {
	int z;
	
	Point3D(int x, int y, int z){
		// 자신 멤버 초기화 
		this.z = z;
        
		/*
		조상 멤버 초기화
		this.x = x;
		this.y = y;
		*/
        
		// 조상의 생성자를 호출해 초기화하는것이 더 바람직
		super(x, y);
	}
}

 

3. super() 조상 생성자 조건

생성자의 첫 줄에 반드시 생성자 호출 → 미호출시 컴파일러가 자동으로 첫줄에 super(); 삽입함

 

728x90