열렬히.뛰기

오버라이딩 (= 덮어쓰기)

Language > 프로그래밍 언어 > Java > 오버라이딩 (= 덮어쓰기)

오버라이딩이란?

조상 클래스의 메소드를 변경하는 것을 오버라이딩이라고 한다.

예시 : 오버라이딩

java
class libft {
	int atoi(String x) {
		x.toint();
	}
	memchr();
	itoa();
}

// atoi라는 함수를 바꿔보자.

class libft_pro extends libft {
	int atoi(String x) {
		x.toint() + 1;
	}
}

오버라이딩의 규칙

  1. 이름이 같아야 한다.

  2. 매개변수와 반환타입이 같아야 한다.

  3. 조상 클래스의 접근 제어자보다 좁게 변경할 수 없다.

    조상 : protected → 자식 : protected, public.

  4. 조상 클래스의 메소드보다 더 많은 예외를 선언해 줄 수 있다.

오버로딩 vs 오버라이딩

오버로딩 : 한 클래스 안에 여러 개의 메소드를 작성

오버라이딩 : 부모 클래스의 메소드를 바꾸는 것.

super과 super()

super

  • 참조변수의 일종
  • 상속받은 멤버변수와 자신만의 멤버의 이름이 같을 때 쓰는 구분자.
java
class Parent {
	int x = 10;
}

class Child extends Parent {
	int x = 20;
	void start() {
		int x = 30;
		system.out.println(x);       // 결과는 20
		system.out.println(this.x);  // 결과는 30
		system.out.println(super.x); // 결과는 10
	}
}

다음 코드를 보고 this와 super의 차이를 이해해보자.

  • 이름 같고, 같은 클래스 : this
  • 이름 같고, 상위 클래스 : super

물론, 아래와 같이 메소드도 super을 쓸 수 있다.

java
class point {
	int x;
	int y;
	int distance(int x, int y) {
		return x - y;
	}
}

class point3D extends point {
	int z;
	int distance(int x, int y, int z) {
			return distance.super(x, y) - z;
	}
}

super()

조상 클래스의 생성자

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

class partition extends point {
	int z;
	point3D(int x, int y, int z) {
		super(x, y);
		this.z = z;
	}
}

this() : 같은 클래스, 다른 생성자

super() : 상위 클래스