一、Object
1、它是所有类默认的直接或者间接的父类, 不必显式的表示出来;
2、该类中定义了所有类都具备的方法;
3、Object中的equals()方法:因为Object类中是比较两个对象的内存地址值,意义不大;所以可以通过
覆盖Object类的equals()方法,建立自己定义类特有比较内容;利用多态的机制实现比较。
例子:ObjectDemo.java
- class Demo //默认extends Object
- {
- private int num;
- Demo(int num)
- {
- this.num = num;
- }
- public boolean equals(Object obj)
- {
- if(!(obj instanceof Demo))
- return false;
- Demo d = (Demo)obj;
- return this.num == d.num;
- }
- /*
- public boolean compare(Demo d)
- {
- return this.num==d.num;
- }
- */
- }
- class Person //默认extends Object
- {
- }
- public class ObjectDemo
- {
- public static void main(String[] args)
- {
- Demo d1 = new Demo(4);
- Demo d2 = new Demo(7);
- System.out.println(d1.equals(d2));
- Person p = new Person();
- System.out.println(d1.equals(p));
- }
- }
4、Object中的getClass()方法:
返回创建此类的类Class的对象
例子:ObjectDemo1.java
- class Demo {//默认extends Object
- private int num;
- Demo(int num)
- {
- this.num = num;
- }
- public boolean equals(Object obj)
- {
- if(!(obj instanceof Demo))
- return false;
- Demo d = (Demo)obj;
- return this.num == d.num;
- }
- }
- class Person {//默认extends Object
- }
- public class ObjectDemo1 {
- public static void main(String[] args)
- {
- Demo d1 = new Demo(4);
- Class c = d1.getClass();
- System.out.println(c.getName());
- }
- }
- //结果:Demo
5、Object中的toString()方法:返回对象的名称@ 哈希值字符串,意义不大,所以可以通过
覆盖Object中的toString()方法,返回自己想要输出的内容。
例子:ObjectDemo2.java
- class Demo {//默认extends Object
- private int num;
- Demo(int num)
- {
- this.num = num;
- }
- public boolean equals(Object obj)
- {
- if(!(obj instanceof Demo))
- return false;
- Demo d = (Demo)obj;
- return this.num == d.num;
- }
- public String toString(){
- return "Demo:"+num;
- }
- }
- class Person {//默认extends Object
- }
- public class ObjectDemo2{
- public static void main(String[] args)
- {
- Demo d1 = new Demo(4);
- System.out.println(d1.toString());
- Demo d2 = new Demo(7);
- System.out.println(d2.toString());
- }
- }
- //结果:
6.