Object类

getClass方法

  • 返回引用中存储的实际对象类型

  • 应用:通常用于判断两个引用中实际存储对象类型是否一致

public static void main(String[] args) {
       Student s1 = new Student();
       Student s2 = new Student();
       s1.age=11;
       s1.name="aaa";
       s2.age=11;
       s2.name="aaa";
       //判断s1和s2是不是同一个类型
       Class class1 =s1.getClass();
       Class class2 =s2.getClass();
       if(class1==class2){
           System.out.println("属于同一类型");
      }else{
           System.out.println("不属于同一类型");
      }
       System.out.println(s1.equals(s2));
  }

 

hashCode()方法

  • 返回该对象的哈希码值

  • 一般情况下相同的对象返回相同的哈希码值

//hashcode方法
System.out.println(s1.hashCode());//1324119927
System.out.println(s2.hashCode());//990368553

 

toString()方法

  • 返回该对象的字符串表示

  • 可以根据程序要求覆盖该方法,如展示对象各属性值

equals()方法

  • 比较两对象地址是否相同

  • 可进行覆盖,比较两对象的内容是否相同

public class Student {
   String name;
   int age;
   public String getName(){
       return name;
  }
   public int getAge(){
       return age;
  }
   public boolean equals(Object obj){
       //1.判断两对象是否为同一引用
       if(this==obj){
           return true;
      }
       //2.判断obj是否为null
       if(obj==null){
           return false;
      }
       //3.判断是否是同一个类型
        /*
           if(this.getClass()==obj.getClass()){}
        */
       if(obj instanceof Student){//instanceof 判断对象是否是某种类型
           //4.强制类型转换
           Student s = (Student)obj;
           if(this.name.equals(s.getName())&&this.age==s.getAge()){
               return true;
          }
      }
       return false;
  }
}
public class Application {
   public static void main(String[] args) {
       Student s1 = new Student();
       Student s2 = new Student();
       s1.age=11;
       s1.name="aaa";
       s2.age=11;
       s2.name="aaa";
       System.out.println(s1.equals(s2));//true
  }
}

 

posted @ 2022-03-27 20:10  CC&  阅读(28)  评论(0)    收藏  举报