woaidongmao

文章均收录自他人博客,但不喜标题前加-[转贴],因其丑陋,见谅!~
随笔 - 1469, 文章 - 0, 评论 - 661, 引用 - 0
数据加载中……

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.

posted on 2009-06-17 10:04 肥仔 阅读(512) 评论(0)  编辑 收藏 引用 所属分类: Web-后台


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理