overriding - 덮어쓰다
상소받은 조상의 메서드를 자신에 맞게 변경하는것
- 선언부가 조상 클래스의 메서드와 일치해야 한다.
- 접근 제어자를 조상 클래스의 메서드보다 좁은 범위로 변경할 수 없다.
- 예외는 조상 클래스의 매서드보다 많이 선언할 수 없다.
class Mypoint3 {
int x;
int y;
String getLocation() {
return "x:" +x+", y:" +y;
}
}
class MyPoint3D extends MyPoint3{
int z;
// 조상의 getLocation()을 오버라이딩 //호출부만 가능
String getLocation() {
return "x:" +x+", y:" +y+", z:"+z;
}
}
public class OverrideTest {
public static void main(String[] args) {
MyPoint3D p = new MyPoint3D();
p.x = 3;
p.y = 5;
p.z = 7;
System.out.println(p.getLocation());
}
}
Object클래스 toString()을 오버라이딩
class Mypoint3 {
int x;
int y;
MyPoint3(int x, int y){
this.x = x;
this.y = y;
}
}
// Object클래스의 toString()을 오버라이딩
public String toString() {
return "x:" +x+", y:" +y;
}
}
public class OverrideTest {
public static void main(String[] args) {
MyPoint3D p = new MyPoint3D(3, 5);
System.out.println(p);
}
}
'JAVA' 카테고리의 다른 글
객체지향 super() - 조상의 생성자 (0) | 2022.09.26 |
---|---|
객체지향 참조변수 super (0) | 2022.09.26 |
객체지향 포함 관계 (0) | 2022.09.25 |
객체지향 상속(inheritance) (1) | 2022.09.25 |
객체지향 변수의 초기화 (1) | 2022.09.25 |