[자바]toString

Nux·2022년 6월 14일
0

toString()

  • 객체 정보를 문자열로 리턴
  • 오버라이딩해서 사용해야 함
    • 오버라이딩 없이 바로 사용시 객체이름@16진수해시코드형식으로 출력

예시

  • VO에서 선언하여 오고가는 값(setter, getter) 확인 가능

선언

public class StudentVO{
	private String name;
    private int age;
    
    public String getName(){
    	return name;
    }
    public void setName(String name){
    	this.name = name;
    }
    
    public int getAge(){
    	return age;
    }
    public void setAge(int age){
    	this.age = age;
    }
    
    @Override
    public String toString(){
    	return "StudentVO[name="+name+", age="+age+"]";
    }
}

호출

public class Test{
	public static void main(String[] args){
    	StudentVO studentVO = new StudentVO();
        
        studentVO.setName("홍길동");
        studentVO.setAge(27);
        
        System.out.println(studentVO.toString());
    }
}

출력값: StudentVO [name=홍길동, age=27]
오버라이딩 없이 실행 시: 패키지경로.StudentVO@2d484fb3

0개의 댓글