ObjectでのtoStringメソッド

3038 ワード

ObjectでのtoStringメソッド
 
 
Objectクラスがすべてのクラスのベースであるデフォルトでは、すべてのクラスが継承されます.
ObjectクラスにはtoStringメソッドが存在します.この方法は隠れています.私たちはよく使いますが、注意したことがありません.
eg:
public class Test{
public static void main(String args[]){
int a=100;
int b=200;
int c;
c=a+b;
System.out.println("a+b= "+c);
}
}
上記の簡単な例では、私たちのcのような整形を文字列に変換して出力します.デフォルトのtoStringメソッドでは、ベースクラスの継承メソッドが使用されています.
しかし、参照タイプを印刷するには、予想される効果に達しない可能性があります.例を見てください.
public class Test{
public static void main(String args[]){
Dog d=new Dog();
System.out.println("d:="+d);
}
}
class Dog{
}
このように実現するとhashcode、つまりメモリ内の位置が印刷されます.どうすればいいですか?
TOStringメソッドを書き直さなければなりません
修正して
public class Test{
public static void main(String args[]){
Dog d=new Dog();
System.out.println("d:="+d);
}
}
class Dog{
public String toString(){
return "is a hot dog";
}
}
TOStringメソッドを書き換えるとis a hot dogが正常に印刷されます
リファレンスタイプを出力する必要がある場合は、常にtoStringメソッドを使用する必要があります.
 
//----付録、Objectの方法protected  Object clone()           Creates and returns a copy of this object. boolean equals(Object obj)           Indicates whether some other object is "equal to"this one. protected  void finalize()           Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. Class<?> getClass()           Returns the runtime class of this Object . int hashCode()           Returns a hash code value for the object. void notify()           Wakes up a single thread that is waiting on this object's monitor. void notifyAll()           Wakes up all threads that are waiting on this object's monitor. String toString()           Returns a string representation of the object. void wait()           Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. void wait(long timeout)           Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. void wait(long timeout, int nanos)           Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.