JAVA
객체지향 메서드 오버라이딩(overriding)
연93
2022. 9. 25. 21:06
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);
}
}