오버라이딩(overriding)

essential·2023년 7월 16일

객체 지향

목록 보기
19/40

오버라이딩(overriding)

  • 상속 받은 조상의 메서드를 자신에 맞게 변경하는 것
  • 정확히는 메서드 오버라이딩임
class Point {
	int x;
	int y;

	String getLocation() {
			return "x : " + x + ", y : " + y;
	}
}

class Point3D extend Point {
	int z;

	String getLocation() { 
//오버 라이딩
//내용만 변경 가능, 구현부 {} / 선언부 변경 불가
			return "x : " + x + ", y : " + y, z : " + z;
	}
}

ex.OverrideTest

class Point {
	int x;
	int y;

	String getLocation() {
			return "x : " + x + ", y : " + y;
	}
}

class Point3D extend Point {
	int z;
	// 조상의 getLocation()을 오버라이딩
	String getLocation() { 
				return "x : " + x + ", y : " + y, z : " + z;
		}
}

public class OverrideTest {
	public static void main(String[] args) {
		Point3D p = new Point();
		p.x = 3;
		p.y = 5;
		p.z = 7;
		System.out.println(p.getLocation());
	}
}

오버라이딩의 조건

  • 선언부가 조상 클래스의 메서드와 일치해야 한다.
class point {
	int x;
	int y;
	String getLocation() {
	}
}

class Point3D extends Point {
	int z;
	String getLocation() {
	}
}

//선언부(반환타입, 메서드이름, 매개변수 목록)일치
  • 접근 제어자(public, protected, default, private)를 조상 클래스의 메서드보다 좁은 범위로 변경할 수 없다.
  • 예외는 조상 클래스의 메서드 보다 많이 선언할 수 없다.

오버로딩 vs 오버라이딩

오버로딩(overloading) : 기존에 없는 새로운 메서드를 정의하는 것(new)

오버라이딩(overriding) : 상속받은 메서드의 내용을 변경하는 것(change, modify)

class Parent {
		void parentMethod() {
}

class Child extend Parent {
		 void parentMethod() {} // 오버라이딩
		 void parentMethod(int i) {} //오버로딩
		 void childMethod() {} //메서드 정의
		 void childMethod(int i) {} //오버로딩
		 void childMethod() {} //중복 정의
profile
essential

0개의 댓글