✅ 오버라이딩 ✅ vs오버로딩 ✅ super
(overriding)
조상 클래스로부터 상속받은 메서드를 (자손 클래스) 자신에 맞게 변경하는 것
class Point{
int x;
int y;
String getLocation(){
return x+y;
}
}
class Point3D ectends Point{
int z;
String getLocation(){ // 오버라이딩
return x+y+z;
}
}
조상 클래스의 메서드와
- 이름이 같아야 한다.
- 매개변수가 같아야 한다.
- 반환타입이 같아야 한다.
(한마디로 선언부가 일치해야 한다.)
접근 제어자와 예외는 제한된 조건 하에서 다르게 변경할 수 있다.
오버로딩 (overloading) : 기존에 없는 새로운 메서드를 정의하는 것
오버라이딩 (overriding) : 상속받은 메서드의 내용을 변경하는 것
class Parent{
void parentMethod() {}
}
class Child extends Parent{
void parentMethod() {} // 오버라이딩
void parentMethod(int i) {} // 오버로딩
void childMethod()
void childMethod(int i) // 오버로딩
}
자손 클래스에서 조상 클래스로부터 상속받은 멤버를 참조하는데 사용되는 참조변수
package ch07;
public class Super {
public static void main(String[] args) {
Child c = new Child();
c.method();
}
}
class Parent{
int x = 10;
}
class Child extends Parent{
int x = 20;
void method(){
System.out.println("x="+x);
System.out.println("this.x="+this.x);
System.out.println("super.x="+super.x);
}
}
결과
x=20
this.x=20
super.x=10
Object 클래스를 제외한 모든 클래스의 생성자 첫 줄에 생성자.this() 또는 super()을 호출해야 한다. 그렇지 않으면 컴파일러가 자동적으로 super() 을 생성자의 첫 줄에 삽입한다.
(자세한 매커니즘은 2회독때 알아보도록 하자.)