刚开始学习Java,首先对Object类做一个大致的了解。
代码如下,基本的方法我都已经覆盖了(除了wait方法,目前还不知道是用来干嘛的。。。后续更新吧)
public class ObjectTest implements Cloneable
{
private int num;
public ObjectTest()
{
this(0);
}
public ObjectTest(int i)
{
num = i;
}
public String toString()
{
//将数字转成字符串的几种方法
String s = new String(""+num); //1.
//String s = String.valueOf(num); //2.
//String s = new Integer(num).toString(); //3.
return s;
}
/*需要实现Cloneable接口,并处理异常*/
public Object clone()
{
ObjectTest obj = null;
try{
obj = (ObjectTest)super.clone();
}catch(CloneNotSupportedException e)
{
e.printStackTrace();
}
return obj;
}
/**
此方法的实现逻辑较为复杂
如果不覆盖此方法,那么equals方式默认的实现与==相同
*/
public boolean equals(Object obj)
{
if(this == obj)
return true;
if(obj == null)
return false;
if(getClass() != obj.getClass())
return false;
ObjectTest other = (ObjectTest)obj;
return this.num==other.num;
}
public int hashCode()
{
return 37*num;
}
/*这个方法不懂怎么调用*/
public void finalize()
{
System.out.println("finalize!");
}
public static void main(String[] arg)
{
ObjectTest obj1 = new ObjectTest(1);
//测试toString方法
System.out.println(obj1);
//测试clone方法
ObjectTest obj2 = (ObjectTest)obj1.clone();
System.out.println(obj1);
//测试equals方法
if(obj1.equals(obj2))
{
System.out.println("Equal!");
}else{
System.out.println("Not equal!");
}
//测试hashcode方式
System.out.println("obj1 = "+obj1.hashCode());
System.out.println("obj2 = "+obj2.hashCode());
//测试getClass方法
Class c = obj1.getClass();
System.out.println("obj1.getClass() "+c);
System.out.println("c.getName() "+c.getName());
System.out.println("c.getSuperclass() "+c.getSuperclass());
Class[] interfaceclass = c.getInterfaces();
for(int i=0;i<interfaceclass.length;i++)
{
System.out.println("Interfaces "+interfaceclass[i].getName());
}
}
}