Java-Object类

Object类

  • Object :所有类的根类
  • Object 是抽取而来的,具备着所有对象都具备的共性内容
  • 常用的共性内容:
    • equals 方法
    • hashCode 方法
    • getClass 方法
    • toString 方法

      equals方法

  • equals 实现对象上差别可能性最大的相等关系,即,对于任何非空引用值 x 和 y ,当且仅当 x 和 y引用同一个对象时,此方法才返回 true (x==y 具有值 true)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    public class Person {
    private int age;
    public Person(int age){
    this.age = age;
    }
    }
    public class ObjectDemo {
    public static void main(String[] args){
    Person p1 = new Person(20);
    Person p2 = new Person(20);
    Person p3 = p1;
    System.out.println(p1==p2);
    System.out.println(p1.equals(p2));
    System.out.println(p1.equals(p3));
    }
    }
  • equals 方法重写,比较成员变量值

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    public class Person {
    private int age;
    public Person(int age){
    this.age = age;
    }
    /*
    一般都会覆盖此方法,根据对象的特有内容,建立判断对象是否相同的依据
    */
    public boolean equals(Object obj){//会将参数中的对象进行向上转型
    //为了提高程序鲁棒性,进行判断
    if (!(obj instanceof Person)){
    throw new ClassCastException("类型错误");
    }
    //为了使用子类的私有方法,进行向下转型
    Person p = (Person) obj;
    return this.age == p.age;
    }
    }

hashCode方法

  • 先演示一下功能,发现运行后的结果很相似,发现hashCode的结果是16进制地址值的10进制数。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    public class ObjectDemo {
    public static void main(String[] args){
    Person p1 = new Person(20);
    System.out.println(p1);
    System.out.println(p1.hashCode());
    System.out.println(Integer.toHexString(p1.hashCode()));
    //Person@1540e19d
    //356573597
    //1540e19d
    }
    }
  • hashCode可以进行重写,在person类中加入如下的代码,ObjectDemo运行的结果会发生变化

    1
    2
    3
    4
    5
    6
    public int hashCode(){
    return age;
    }
    //Person@14
    //20
    //14

getClass方法

  • 字节码文件是经过编译器预处理过的一种文件,是JAVA的执行文件存在形式,它本身是二进制文件,但是不可以被系统直接执行,而是需要虚拟机解释执行,由于被预处理过,所以比一般的解释代码要快,但是仍然会比系统直接执行的慢
  • 人中抽出Person,class抽取出Class(字节码文件类名)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public class ObjectDemo {
    public static void main(String[] args){
    Person p1 = new Person(20);
    Person p2 = new Person(40);
    Class claz1 = p1.getClass();
    Class claz2 = p2.getClass();
    System.out.println(claz1.equals(claz2));
    //true
    }
    }

toString方法

  • 这是一个改写字符串方法

    1
    2
    3
    4
    5
    6
    7
    public class ObjectDemo {
    public static void main(String[] args){
    Person p1 = new Person(20);
    System.out.println(p1);
    System.out.println(p1.getClass().getName()+"@"+Integer.toHexString(p1.hashCode()));
    }
    }
  • 运行结果:Person@1540e19d Person@1540e19d

  • 其实这就是没改写前方法的功能,我们也可以自己进行改写

    1
    2
    3
    public String toString(){
    return "Person:"+age;
    }
  • 这样改写后输出 p1 的结果就是 Person:20