Friday, February 27, 2009

Object类

在java中所有的对象都扩展自java.lang.Object类。Object类是Java程序中所有类的父类,每个类都直接或间接继承自Object类。

由于Object类是Java中所有类的父类。所以使用Object声明的名称,可以参考至任何的对象而不会发生任何错误,因为每个对象都是Object的子对象。

可以制作一个简单的集合类,并将一些自定义的实例加入其中

public class SimpleCollection {
private Object[] objArr;
private int index=0;

public SimpleCollection(){
objArr=new Object[10];
}
public SimpleCollection(int capacity){
objArr=new Object[capacity];
}
public void add(Object o){
objArr[index]=o;
index++;
}
public int getLength(){
return index;
}
public Object get(int i){
return objArr[i];
}

}



public class Foo1 {
private String name;
public Foo1(String name){
this.name=name;
}

public void showName(){
System.out.println("foo1 名称:"+name);
}

}


public class Foo2 {
private String name;
public Foo2(String name){
this.name=name;
}

public void showName(){
System.out.println("foo2 名称:"+name);
}

}

public class SimpleCollectionDemo {


public static void main(String[] args) {
SimpleCollection simpleCollection=new SimpleCollection();
simpleCollection.add(new Foo1("num.1 Foo1"));
simpleCollection.add(new Foo2("num.2 Foo2"));

Foo1 f1=(Foo1) simpleCollection.get(0);
f1.showName();

Foo2 f2=(Foo2) simpleCollection.get(1);
f2.showName();
}

}










在程序中,SimpleCollection对象可以加入任何类型的对象置其中,因为所有对象都是Object的子对象。从SimpleCollection指定索引取回对象时,要将对象的类型从Object转换为原来的类型,这样就可以实现对象上的方法

Object类定义了几个方法,包括
protected的 clone()、finalize()
public的equals()、toString()、hashCode()、notify()、notifyAll()、wait()、getClass()等
其中,notify()、notifyAll()、wait()、getClass()等方法被声明为final,所以无法重写






Object的toString()方法是对对象的文字描述,它会返回String实例。在定义对象之后可以重写toString()方法,为对象提供特定的文字描述,Object的toString()会默认返回类名称和十六进制的编码也就是返回:

getClass.getName()+’@’+Integer.toHexString(hashCode())

getClass()方法是Object中定义的方法,它会返回对象于执行时期的Class实例,再使用Class实例的getName()方法可以取得类名称;

hashCode()返回该物件的哈希码,哈希码由哈希函数计算得到,在数据结构上可用于数据的寻址。

equals()本身是比较对象的内存地址是否相等,可以定义自己的对象在什么条件下可视为相等的对象。在重写equals()方法时,建议同时重写hashCode()方法,因为在以哈希码为基础的环境中,需要比较两个对象是否为相同的对象时,除了使用equals()之外,还会依hashCode()方法来作判断

import java.util.Date;
public class Cat {
private String name;
private Date birthday;

public Cat(){}

public void setName(String name){
this.name=name;
}

public String getName(){
return name;
}

public void setBirthday(Date birthday){
this.birthday=birthday;
}

public Date getBirthday(){
return birthday;
}

public boolean equals(Object other){
if(this==other)
return true;

if(!(other instanceof Cat))
return false;
final Cat cat=(Cat) other;

if(!getName().equals(cat.getName()))
return false;
if(!getBirthday().equals(cat.getBirthday()))
return false;
return true;
}

public int hashCode(){
int result=getName().hashCode();
result=29*result+getBirthday().hashCode();
return result;
}

}

No comments:

Post a Comment