object类

本文介绍了Java中Object类,它是所有类的父类,默认继承。还重点讲解了Object类中常用的equals方法,对比了“==”和equals方法在基本数据类型和引用数据类型比较时的差异,分析了equals方法重写前后的不同作用,并通过代码示例展示了具体效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

object是比较特殊的类,是所有类的父类,当一个类被创建后没有指定继承的父类,那么默认继承object类

例:public class person{}和public class person extends object{}是一样的

object中常用的两个方法equals()和string()

一、equals()方法

      在学习听课过程中对equals很不理解,尤其是重写前后的作用以及和“==”的区别

      (1)“==”的含义

            基本数据类型:byte、short、int、long、double、float、Boolean、char之间比较的是值

            引用数据类型:比较的是在内存中的存储地址

     (2)equals()

              equals方法不能比较基本数据类型,只能比较引用数据类型

             equals的源码:      public Boolean equals(object obj){

                                                         return(this==obj);                

                                                }

                  初始默认行为是比较数据存储地址是否相同,但是我们用的时候一般是让比较属性值是否相同,这时候就要根据需求进行重写,一般重写就是自动生成的,我们只需用就行

第一种,没有重写,比较数据的存储地址

public class person {
   private String name;
   private int age;
 
public person() {}
   public person(String name,int age) {
       this.name=name;
       this.age=age;
   }
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
}
测试类:

public class test {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
       person p=new person("徐",18);
      person p1=new person("徐",18);
      boolean b=p.equals(p1);
      System.out.println(b);
    }
}

p和p1的地址不同,返回值为false

第二种:equals被重写

public class person {
   private String name;
   private int age;
 
public person() {}
   public person(String name,int age) {
       this.name=name;
       this.age=age;
   }
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
@Override

//重写的equals方法
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    person other = (person) obj;
    if (age != other.age)
        return false;
    if (name == null) {
        if (other.name != null)
            return false;
    } else if (!name.equals(other.name))
        return false;
    return true;
}
}

测试类:

public class test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
       person p=new person("徐",18);
      person p1=new person("徐",18);
      boolean b=p.equals(p1);
      System.out.println(b);
    }
}

对象p的name和age与对象p1的name和age的值相等,b的值为true;

转载于:https://www.cnblogs.com/fbbg/p/10555805.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值