现在的位置: 首页 > 综合 > 正文

对 Object 类中方法的一些简单认识

2013年10月28日 ⁄ 综合 ⁄ 共 2274字 ⁄ 字号 评论关闭
说到toString()方法,就不得不先看看Object类.
Object 类是一个超级类,是一切类的父类;看看sun的JDK就知道,其实他的方法并不多,但都非常实用.
我始终对Object有一丝神秘感,昨天朋友问起Clone()仍有很多困惑;
所以今天决定,来揭开Object的面纱.下面就是我通过翻阅资料和阅读JDK后,对Object的一些理解,如有错误请指出:
package java.lang;
public class Object { }
在JDK1.4中它有11个方法,主要的方法有 clone(), equals(), getClass(), notfiy(), toString(), wait() .......
我在这里只重点说说clone(), equals(),  toString()
1.clone()
所有具有clone功能的类都有一个特性,那就是它直接或间接地实现了Cloneable接口。否则,我们在尝试调用clone()方法时,将会触发CloneNotSupportedException异常。
protected native Object clone() throws CloneNotSupportedException;(在JDK中)
可以看出它是一个protected方法,所以我们不能简单地调用它,
native : 关键字native,表明这个方法使用java以外的语言实现。所修辞的方法不包括实现.   (参考:http://blog.csdn.net/mingjava/archive/2004/11/14/180946.aspx)
在这里我就不具体讲clone() 是如何实现Cloneable接口,如何覆盖; 这说说clone的作用和用法;
对于 object  x,
x.clone() != x
x.clone().getClass() == x.getClass()
x.clone().equals(x)
x.clone().getClass() == x.getClass()
以上返回的值都为true 
2 equals()
其原型为:
public boolean equals(Object obj) {
      return (this == obj);
 }
Object 中定义的 equals(Object) 是比较的引用,与 "==" 作用相同。
3. toString()其原型为:
public String toString() {
   return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
toString() 方法是最为常见的,在很多类中都对他进行覆盖:
先看两个例子
例一:     
class Example{
    private String s = "abc";
    public Example(String str) {
    this.s = str + this.s ;
 }
 public static void main(String[] args){
     Example ex = new Example("123");
     System.out.println(ex);
     System.out.println(ex.s);
 }
 public String toString() {
     this.s = "cba" +this.s;
     return s;
}
输出结果: 
cba123abc
cba123abc
例二.
class Example{
    private String s = "abc";
    public Example(String str) {
    this.s = str + this.s ;
 }
 public static void main(String[] args){
     Example ex = new Example("123");
     System.out.println(ex);
     System.out.println(ex.s);
 }
 public String toString2() {
     this.s = "cba" + this.s;
     return s;
}
输出结果:
Example@1858610
123abc
例一:和例二;只修改了tostring的方法名,但执行却有很大的不同 ;
例一中: tostring()被覆盖,在执行new Example("123");的时候,先调用构造方法(暂不执行)再加载执行父类中的方法tostring()(这里被覆盖,则运行本类中的方法代码),最后执行构造方法;这里涉及到执行的顺序,不着讨论;  然后在执行到 System.out.println(ex); 时,实际是打印方法tostring()返回的string值;
在例二中:tostring()并没有被覆盖,toString2() 是类中普通的方法, 所以new Example("123");时,不会加载执行toString2() ,所以s值为"123abc";而System.out.println(ex);打印出来的结果,是原型中看到的 类名 + @ + 十六进制数字表示的该对象的散列码
方法tostring()使用还很多,我们在编写类的时候,都最好能有自己的tostring,把原型覆盖掉;

抱歉!评论已关闭.