1、Object类是所有Java类的基类
位于C:\Program Files (x86)\Java\jre7\lib\rt.jar\java\lang
文档下载:http://java.sun.com>>Java SE>>download>>jdk-7u17-apidocs.zip
解压到C:\Program Files (x86)\Java\jdk1.7.0_09
查看:index.html>>Java SE API>>java.lang>>Object
2、如果在类的声明中未使用extends关键字指明其基类,则默认基类为Object类
public class Person
{
}
等价于
public class Person extends Object
{
}
toString方法:
1、Object类中定义有public String toString()方法,其返回值是String类型,描述当前对象的有关信息。
2、在进行String与其他类型数据的连续操作时,(如System.out.println("info"+person)),将自动调用该对象的toString()方法。
3、可以根据需要在用户自定义类型中重写toString()方法。
---
public class TestToString
{
public static void main(String[] args)
{
Dog d = new Dog();
Cat c = new Cat();
System.out.println("d: "+d.toString());
System.out.println("c: "+c.toString());
System.out.println("c: "+c);
}
}
class Dog
{
public String toString()//overwrigt//copy
{
return "I'm a cool Dog.";
}
}
class Cat
{
}
---
在Object类中有toSting成员函数,建议使用者重写该成员函数。默认的toString()返回值为:类名@哈希编码。
哈希编码:
在JAVA虚拟机里有一张表,记录了所有对象。即哈希编码,独一无二的记录了对象,根据哈希编码能找到对象在内存中的位置。
(有时候,不同的对象可能有相同的哈希编码)
如果系统中,你编写了很多Dog.class,而编译的时候,系统按照Classpath的顺序来查找Dog.class,所以很容易出错。
Eclipse可以避免这个问题。
equals方法:
Object类中有定义:
1、public boolean equals(Object obj)方法
提供定义对象时候“相等”的逻辑。
2、Object 的equals方法定义为: x.equals( y ) 当x和y 是同一个对象的应用时返回true,否自返回false.
3、J2SDK提供的一些类,如String,Date等,重写了Object的equals方法,调用这些类的equals方法,x.equals( y ) ,当x和y所引用的对象是同意对象且属性内容相等时(并不一定是相同对象),返回true否则返回false。
4、可以根据需要在用户自定义类型中重写equals方法。
----
public class TestEquals
{
public static void main(String[] args)
{
Cat c1 = new Cat(1,2,3);
Cat c2 = new Cat(1,2,3);
System.out.println(c1 == c2);
}
}
class Cat
{
int color;
int height;
int weight;
public Cat(int color, int height,int weight)
{
this.color = color;
this.height = height;
this.weight = weight;
}
}
----
这两只猫打死不一样。因为在内存中是完全不同的两个位置。
要比较这两只猫是不是相同。
System.out.println(c1.equals(c2));也不可能相同。
equals的使用默认是:只有c1和c2指向同一对象时,才返回true。
只有重写equals()
---
public class TestEquals
{
public static void main(String[] args)
{
Cat c1 = new Cat(1,2,3);
Cat c2 = new Cat(1,2,3);
System.out.println(c1.equals(c2));
System.out.println(c1==c2);
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1.equals(s2));
}
}
class Cat
{
int color;
int height;
int weight;
public Cat(int color, int height,int weight)
{
this.color = color;
this.height = height;
this.weight = weight;
}
public boolean equals(Object obj)
{
if(obj == null)
return false;
else
{
if(obj instanceof Cat)
{
Cat c = (Cat)obj;
if(c.color == this.color && c.height == this.height&& c.weight == this.weight)
return true;
}
return false;
}
}
}
----