Back Ground

toString이란? 본문

JAVA

toString이란?

Back 2016. 7. 10. 11:50

Object 이란




모든 클래스의 가장 최상위 클래스인 "Object" 클래스



JAVA에 제공하는 모든 클래스들의 계충 구조로 되어있고, 그 최상위로 올라가면 "Object"이라는 클래스가 존재한다.


우리가 일반적으로 생성하는 클래스도 "extends"로 직접 상속하지는 않지만 

자바 컴파일러는 일반 클래스를 "Object"하위 클래스로 자동 설정하게 되어 있습니다.




즉, 자바 라이브러리나 유저가 만든 모든 클래스는 

"Object" 클래스를 부모클래스로 상속 받아서 사용 하게 됩니다.






toString() 메소드란




"Object"클래스가 가진 메소드 중 "toString"메소드가 있습니다.

물론 "Object" 클래스의 모든 메소드는 모든 클래스가 사용이 가능합니다.

"toString" 메서드는 객체가 가지고 있는 정보나 값들을 문자열로 만들어 리턴하는 메소드 입니다.



이렇게 출력해보면 결과값에는 이상한 정보가 담기는데

이 값은 순수 "Object"의 "toString"결과 값입니다. (결국 의미없는 디폴트 값)






하지만 "String" 클래스나 "File"클래스에서는 "toString"에 메소드를 재정의 하여 의미있는 값을 리턴해 줍니다.







"String" 클래스 객체의 "toString"메소드는 자신이 가진 값을 그대로 리턴해주고,

"File"클래스 객체의 "toString"메소드는 자신이 가진 해당 경로값을 리턴해 주고있습니다.


이 두 클래스는 내부에서 "toString"을 재정의해서 사용한 것 입니다.





증거로는 이클립스 자동완성 창에서 보여줄 수 있습니다.



- "String"클래스의 "toString"메소드 상세 설명 -


빨간 네모 부분 보면 "Overrides : to String in class Object"라고 써 있는데

오버라이드 즉, 재정의했다는 의미 입니다.










toString() 메소드를 재정의해서 사용



( 재정의 : 정의되어 있는 변수나 배열 요소가 다시 정의되는 것 )


아까전 의미없던 값 "Human"클래스로 재정의 해보겠습니다.


콘텍스트 메뉴로 오버라이드할 메소드를 찾을수 있습니다.



ok를 누르면



오러라이딩 함수가 생성되는데

이 함수를 재정의 하여 사용하도록 하겠습니다



빨간 네모처럼 나이를 리턴하도록 만들고

실제로 사용해 보도록 하겠습니다.





"Human"클래스의 객체를 생성하여 "toString" 메소드를 사용해 보았습니다.

우리가 재정의 했던 "toString"메소드가 잘 호출 되었음을 출력값을 통해 알 수가 있습니다.








toString() 메소드는 자동으로 호출된다


toString 매소드는 자동으로 호출 됩니다.


우리가  자주 사용하던 "String" 클래스 객체를 선언하여

"toString"메소드 없이 그냥 객체 자체로 변수에 담긴 내용을 가져와 사용했었습니다.







위 코드를 보시면 "str"이라는 "String"클래스의 객체 입니다.


그런데 신기하게도 객체임에도 불구하고

"str"독단적으로 저렇게 사용 되어지고 있습니다.


바로 이 지점에서 "toString"이 자동으로 호출 되는 것입니다.

이것을 증명하기 위해서 우리가 구현한 "Human"클래스로 한번 시도 해보겠습니다.







아까 만들었던 소스에서 "toString"만 제거 하였습니다.

출력 결과는 잘나오고 있는걸 확인할수 있습니다.


출처: http://blog.naver.com/highkrs/220253206615 모프




What is Object




The " Object " class , the top-level class of all classes



It is a hierarchical structure of all classes provided to JAVA, and when it goes up to the top, there is a class called "Object".


The classes we normally create don't even inherit directly into "extends", 

The Java compiler automatically sets the generic class to the "Object" subclass.




In other words, the Java library or any class created by the user  

The "Object " class is inherited and used as a parent class.






What is the toString() method?




Among the methods that the "Object" class has, is the "toString" method.

Of course, all methods of the "Object" class can be used by all classes.

The " toString " method is a method that returns the information or values ​​the object has as a string.



If you print it like this, the result contains strange information.

This is the result of the "toString" of the pure "Object". (Eventually meaningless default)






However, in the "String" class or the "File" class, the method is overridden in "toString" to return a meaningful value.







The "toString" method of the "String" class object returns its own value,

The "toString" method of the "File" class object returns the value of its path.


These two classes were used by redefining "toString" internally.





Evidence can be shown in the Eclipse autocomplete window.



-Detailed description of the "toString" method of the "String" class-


If you look at the red square, it says "Overrides: to String in class Object"

It means override, that is, redefinition .










Override toString() method



(Redefinition: Defined variable or array element is redefined)


Let's redefine the "Human" class, which was just meaningless.


You can find the method to override in the context menu.



press ok



The auroriding function is created

I'll override this function and use it



Make the age return like a red square

I'll actually use it.





I created an object of the "Human" class and tried using the "toString" method.

You can see from the output that the "toString" method we've overridden is called.








The toString() method is called automatically


The toString method is called automatically.


Declare the "String" class object we used often

Without using the "toString" method, I simply used the contents of the variable as the object itself.







If you look at the code above, it is an object of class "String" called "str".


Interestingly, despite being an object,

"str" ​​is used arbitrarily like that.


At this point, "toString" is called automatically.

To prove this, let's try it with the "Human" class we implemented.







We removed only "toString" from the source we created earlier.

You can see that the output is going well.


Source: http://blog.naver.com/highkrs/220253206615 Morph




Objectと




すべてのクラスの中で最も最上位クラスである「Object」クラス



JAVAに提供するすべてのクラスのギェチュン構造になっており、その最上位に上がれば「Object」というクラスが存在する。


私たちは、一般的に生成するクラスも「extends」に直接継承しませんが、 

Javaコンパイラーは、一般的なクラスを「Object」のサブクラスで自動的に設定することになっています。




つまり、Javaのライブラリやユーザが作成したすべてのクラスは、  

「Object」クラスを親クラスに継承受けて使用します。






toString()メソッドとは




「Object」クラスが持つメソッドのうち、「toString "メソッドがあります。

もちろん「Object」クラスのすべてのメソッドは、すべてのクラスが使用可能です。

toString "メソッドは、オブジェクトが持っている情報や値を文字列にして返すメソッドです。



このように出力してみると、結果の値は、奇妙な情報が追加のに

この値は、純粋な「Object」の「toString "結果の値です。(最終的には意味のないデフォルト値)






しかし、"String"クラスや"File"クラスでは、「toString」にメソッドをオーバーライドするのでは意味のある値を返してくれます。







「String」クラスのオブジェクトの「toString "メソッドは、自分が持っている値をそのまま返すてくれて、

「File」クラスのオブジェクトの「toString "メソッドは、自分が持っている、そのパスの値を返すしています。


この二つのクラスは、内部で「toString "を財政によって使用されます。





証拠には、Eclipseの自動補完ウィンドウで表示することができます。



- "String"クラスの "toString"メソッド詳細 -


赤い四角の部分見れば「Overrides:to String in class Object」と書いてありますが

オーバーライドつまり、財政のという意味です。










toString()メソッドをオーバーライドしてによって使用



(財政の定義されている変数や配列要素が再定義しているもの)


さっき意味なかった値 "Human"クラスで再定義してみましょう。


コンテキストメニューでオーバーライドするメソッドを検索できます。



okを押すと、



オーラライディング関数が生成され

この関数をオーバーライドのして使用するようにします



赤い四角のように年齢を返すように作成し

実際に使ってみましょう。





「Human」クラスのオブジェクトを生成して、「toString "メソッドを使ってみました。

私たちは、財政のだった "toString"メソッドがよく呼び出されたこと出力を介して知ることができます。








toString()メソッドは、自動的に呼び出され


toStringメソッド・は自動的に呼び出されます。


私たちは、頻繁に使用していた「String」クラスのオブジェクトを宣言して

「toString "メソッドずそのままオブジェクト自体に変数に入れられた内容を持ってきて使用しました。







上記のコードを見ると、「str」という "String"クラスのオブジェクトです。


ところが、不思議なことに、オブジェクトにもかかわらず

「str」独断的にあのように使用されています。


まさにこの点で、「toString "が自動的に呼び出されることです。

これを証明するために、私たちが実装した「Human」クラスに一度試してみます。







さっき作ったソースで "toString"だけを削除しました。

出力結果はよく出ていることを確認することができます。


出典:http://blog.naver.com/highkrs/220253206615モーフ



'JAVA' 카테고리의 다른 글

ModelAndView  (0) 2017.06.01
JVM 메모리 구조  (1) 2017.03.09
JAVA - 배열[]  (0) 2017.02.15
GSON - java 객체(object)를 JSON 표현식으로 변환하는 API  (0) 2016.12.20
오버라이딩/오버로딩  (1) 2016.07.10
Comments