Object类

2020-10-30  本文已影响0人  曾梦想仗剑天涯

Object类的基本概念

class Person {} class Person extends Object{}
//Object类接收所有子类对象
class Person {}
public class JavaDemo {
  public static void main(String [] args) {
    Object obj = new Person();  //向上转型
    if(obj instanceof Person) {
      Person per = (Person) obj;
      System.out.println("Person对象向下转型");
    }
  }
}
//使用Object类接收数组
public class JavaDemo {
  public static void main(String [] args) {
    Object obj = new int [] {1, 2, 3};  //向上转型
    if(obj instanceof int []) {
      int [] data = (int []) obj;
      for(int x = 0; x < data.length; x++) {
        System.out.println(data[x]);
      }
    }
  }  
}

获取对象信息toString()

//观察默认的toString()实现
class Person {
  private String name;
  private int age;
  private Person(String name, int age) {
    this.name = name;
    this.agge = age;
  }
  @Override
  public String toString() {
    return "姓名:" + this.name + "、年龄:" + this.age;
  }
}
public class JavaDemo {
  public static void main(String [] args) {
    Person per = new Person();
    System.out.println(per);
    System.out.println(per.toString());  //toString()从Object继承而来
    //可以发现在之前进行对象直接输出的时候,所调用的方法就是toString()方法
    //所以这个方法调用与不调用的效果是一样的
    //所以对象信息的获得可以直接覆写此方法
    //Person per = new Person("张三", 20);
    //System.out.println(per);
  }
}

对象比较equals()

Person perA = new Person("张三", 20);
Person perB = new Person("张三", 20);
if(perA.getName().equals(perB.getName()) && perA.getAge() == perB.getAge()) {
  System.out.println("是同一个对象");
} else {
  System.out.println("不是同一个对象");
}
public boolean equals(Object obj) {
  return (this == obj);
}
class Person {
  private String name;
  private int age;
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
  @Override
  public String toString() {
    return "姓名:" + this.name + "、年龄:" + this.age;
  }
  //此时equals()方法中有两个对象,一个是this 一个是传入的Object
  public boolean equals(Object obj) {
    if(!(obj instanceof Person)) {
      return false;
    }
    if(obj == null) {   //不关心null的比较
      return false;
    }
    if(this == obj) {   //同一个地址
      return true;
    }
    Person per = (Person) obj;  //向下转型,目的是为了获取类中的属性
    return this.name.equals(per.name) && this.age == per.age;
  }
}
public class JavaDemo {
  public static void main(String [] args) {
    Person perA = new Person("张三", 20);
    Person perB = new Person("张三", 20);
    System.out.println(perA.equals(perB));
  }
}
上一篇下一篇

猜你喜欢

热点阅读