java-Object类

Object类是所有类的根类。

一、toString方法

1.作用:返回字符串表示的对象

2.一般会在类中覆盖toString方法,使其返回一个有意义的字符串。

public String toString(){
    return "radius="+getRadius();
}

有了上面的方法之后,System.out.println(circle.toString( ));的输出结果就是:

[circlr] radius=1.2

另外还可以这样写:System.out.println(circle);输出的结果是一样的,因为编译器会自动调用toString方法。

二、equals方法

1.作用:比较两个对象是否相等。

2.格式:

obj1.equals(obj2)

3.该方法比较的是两个对象的引用

Circle c1=new Circle(10), c2=new Circle(10);
System.out.println(c1.equals(c2));

所以上面代码会输出false

4.覆盖equals方法比较对象的内容

public boolean equals(Object obj){
    if(obj instanceof Circle)
        return this.radius==((Circle)obj).radius;
    else
        return false;
}

上面的方法比较的就是圆的半径。

5.在String类中,equals方法是被覆盖的,所以比较的是字符串的内容。

三、hashCode方法

1.作用:返回一个对象的散列码(hash code)值,是一个整数(十进制存储地址)。

2.格式:

Circle c=new Circle(5);
System.out.println(c.hashCode());

四、clone方法

1.作用:克隆一个的对象(创建一个对象的副本)

2.类的对象要克隆,必须得实现Cloneable接口。

Student s1=new Student(101,"LiMing");
Student s2=(Student)s1.clone();

五、finalize方法

1.定义格式:

protected void finalize( ) throws Throwable

2.代码:

//在student类中定义下面的方法
protected void finalize() throws Throwable{
    System.out.println("The object is destroyed.");
}

//在main方法中使用
public static void main(String[] args){
    Student s1=new Student();
    Student s2=new Student();
    s1=null;
    s2=null;
    System.gc();
}

输出:

The object is destroyed.

The object is destroyed.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值