티스토리 뷰

JAVA

toString method

seoca 2019. 1. 8. 14:05



toString

superclass called Object class has toString() method which converts data(mostly numbers) to string.

When System.out.printlf and System.out.print have reference to an object instead of actual string, they call toString method so, the toString method print the string. It describes the object. 

객체가 가진 값을 문자열로 리턴하는 메서드. 객체를 리턴할 때 보여주고자 하는 방식으로 method를 오버라이드해서 보여줄 수 있다. 아래의 예시처럼 단순히 숫자만 불러오는 것이 아니라 숫자를 불러올 때 마다 보여지는 객체를 재정의 할 수있다. 




Example code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Number
{
    private int num1;
    private int num2;
    private int num3;
    
    public Number(int n1,int n2,int n3)
    {
        num1 = n1;
        num2 = n2;
        num3 = n3;
        
        System.out.printf("The numbers are %s\n"this);

    }
    
    public String toString()
    {
        return String.format("%s,%s,%s", num1,num2,num3);
    }
    
     public static void main(String[] args)
    {
    Number num = new Number(24,26,34);
    }
}

cs




Result

The numbers are 24,26,34



'JAVA' 카테고리의 다른 글

Collection framework - ArrayList  (0) 2019.01.17
abstract & Interface in java  (0) 2019.01.17
wrapper class in java  (0) 2019.01.07
String methods in Java  (0) 2019.01.07
Java Generics (runtime error,compile error)  (0) 2019.01.06