class Point{
int x;
int y;
String getLocation(){
return x + "," + y;
}
}
class Point3D extends Point{
int z;
String getLocation(){ // 오버라이딩
return x + "," + y + "," + z;
}
}
생성자, toString 오버라이딩 활용 예제 - 간결해진 코드를 느껴보자
class Point{
int x;
int y;
Point(int x, int y){ // 생성자 선언
this.x = x;
this.y = y;
}
public String toString(){ // 오버라이딩
return x + "," + y;
}
}
public class OverrideTest{
public static void main(String[] args){
Point p = new Point(3, 5); // 생성자 선언했기 때문에 가능
System.out.println(p);
// System.out.println(p.toString); 위와 동일
// 생성자 없을 경우 초기화 방법
// Point p = new Point();
// p.x = 3;
// p.y = 5;
// toString 오버라이딩 하지 않을 경우 출력 방법
// System.out.println(p.x + "," + p.y);
}
}