[Java] 7. 객체지향 프로그래밍 2 #2 오버라이딩(overriding)

2022. 5. 3. 09:06JAVA/Language

1. 오버라이딩이란 무엇인가?

  • 조상 클래스로부터 상속받은 메서드의 내용을 변경하는 것을 의미함
  • 상속받은 메서드를 그대로 사용하지 않고 자식 클래스 자신에 맞게 변경해야 하는 경우 사용함
class Ponit{	// 부모 클래스
	int x, y;
    
    String getLocation(){
		return "x : " + x + ", y : " + y;
	}
}

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

 

2. 오버라이딩의 조건

자식 클래스에서 오버라이딩하는 메서드는 부모 클래스의 메서드와 다음이 같아야 합니다.

  • 이름
  • 매개변수
  • 반환타입

 

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

  • 오버로딩(overloading) : 기존에 없는 새로운 메서드를 정의(new)
  • 오버라이딩(overriding) : 상속받은 메서드의 내용을 변경하는 것(change, modify)
class Parent{
	void parentMethod(){}
}

class Child extends Parent{
    void parentMethod(){}	// 오버라이딩
    void parentMethod(int i){}	// 오버로딩
    
    void childMethod(){}
    void childMethod(int i){} // 오버로딩
}

 

4. super

  • super는 자식 클래스에서 부모 클래스로부터 상속받은 멤버를 참조하는 사용되는 참조 변수
  • 멤버변수와 지역 변수의 이름이 동일할때 this를 붙여서 구별, 상속받은 멤버와 자신의 멤버와 이름이 동일할때는 super를 붙여서 구별
  • 클래스 메서드는 인스턴스와 관련이 없음. 따라서 super 역시 클래스 메서드에서는 사용할 수 없음
public class SuperTest {
	public static void main(String[] args)
	{
		Child c = new Child();
		c.method();
	}
}

class Parent{
	int x = 10;
}

class Child extends Parent{
	int x = 20;
	public void method() {
		System.out.printf("x=%d\n", x);
		System.out.printf("this.x=%d\n", this.x);
		System.out.printf("super.x=%d\n", super.x);
	}
}
x=20
this.x=20
super.x=10

 

5. super() - 조상 클래스의 생성자

  • this()와 마찬가지로 super() 역시 생성자
  • super()는 부모 클래스의 생성자를 호출하는데 사용됨
  • 자식 클래스의 인스턴스 생성시 생성자에서 super()를 호출하여 부모 클래스의 생성자를 실행함
    • 자식 클래스의 멤버가 부모 클래스의 멤버를 사용할 수 있으므로 부모 클래스의 멤버들이 먼저 초기화 되어야 하기 때문입니다.
Object 클래스를 제외한 모든 클래스의 생성자 첫 줄에 생성자, this() 또는 super()를 호출해야합니다.
그렇지 않으면 컴파일러가 자동적으로 'super()'를 생성자의 첫줄에 삽입합니다.

 

Point3D(int x, int y, int z){
    super();	// 만약 super()가 없다면 컴파일러가 자동적으로 삽입함
    this.x = x;
    this.y = y;
    this.z = z;
}

 

super() 예제

public class PointTest {
	public static void main(String[] args)
	{
		Point3D p3 = new Point3D();
		System.out.printf("p3.x = %d\n", p3.x);
		System.out.printf("p3.y = %d\n", p3.y);
		System.out.printf("p3.z	= %d\n", p3.z);
	}
}

class Point{
	int x = 10;
	int y = 20;
	
	public Point(int x, int y) {
		// super()가 생략되지만 컴파일러에 의해 자동 삽입됨. Object 클래스의 공백 생성자 호출
		this.x = x;
		this.y = y;
	}
}

class Point3D extends Point{
	
	int z = 30;
	
	public Point3D() {
		this(100, 200, 300);
	}

	public Point3D(int x, int y, int z) {
		super(x, y);
		this.z = z;
	}
	
}
p3.x = 100
p3.y = 200
p3.z	= 300

 

References

source code : https://github.com/yonghwankim-dev/java_study
Java의 정석, 남궁 성 지음