toString()은 인스턴스의 정보를 문자열로 반환할 목적으로 정의된 것이다. 아래의 코드처럼 참조변수 c를 출력하면, 참조변수 c가 가리키고 있는 인스턴스에 toString()을 호출하여 그 결과를 화면에 출력한다.
toString메서드가 클래스 정의에 있으면 인스턴스를 프린트문에 넣을 때 그냥 자동으로 자바가 해당 메서드의 리턴값을 출력해주는 거야?
네 맞습니다!
• toString() 메서드를 오버라이드하면 객체를 문자열로 표현할 때 원하는 형식으로 출력할 수 있습니다.
• System.out.println() 등에서 객체를 출력하면 toString()이 자동으로 호출됩니다.
• 만약 toString()을 오버라이드하지 않으면, 기본적으로 클래스 이름 + 해시코드가 출력됩니다.
조상 클래스의 메서드의 내용에 추가적으로 작업을 덧붙이는 경우라면 이처럼 super를 사용해서 조상클래스의 메서드를 포함시키는 것이 좋다. 후에 조상클래스의 메서드가 변경되더라도 변경된 내용이 자손클래스의 메서드에 자동적으로 반영될 것이기 때문이다.
class Point{
int x;
int y;
String getLocation(){
return "x: " + x + ", y :" + y;
}
}
class Point3D extends Point{
int z;
String getLocation(){ // here we wanna 'add' some more features
// return "x: " + x + ", y :" + y;
return super.getLocation();
}
}
super() should be come first line of the constructor of the every classes excepts Object class, which is only one doesn't having super class.
Super() constructor comes every first line and calls the this() of super class. Ofcourse! if there is no this() class for super class, calling it occurs an error.
public class PointTest {
public static void main(String[] args) {
Point3D p3 = new Point3D(1, 2, 3);
}
}
class Point{
int x;
int y;
Point(int x, int y){
this.x = x;
this.y = y;
}
String getLocation(){
return "x: " + x + ", y :" + y;
}
}
class Point3D extends Point{
int z;
Point3D(int x, int y, int z){
this.x = x;
this.y = y;
this.z = z;
}
String getLocation(){
return "x: " + x + ", y :" + y;
}
}
{
super(x, y);
this.z = z;
}