JAVA基础笔记 根类 Object

Object说明

Java中有一个比较特殊的类Object,JDK文档有详细的描述,如果有能力建议直接阅读文档,会有很大的帮助。

Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
Object类是所有类的根类,每个类都把object当作父类,所有的对象都是实现了Object类中方法的,包括数组。

Object类中有11中方法,挑选了几个比较常见的。剩下的是一些多线程的方法,暂时还没有学到。

protected Object clone()
Creates and returns a copy of this object.
创建并返回这个对象的副本

boolean equals(Object obj)
Indicates whether some other object is “equal to” this one.
最常用的比较方法,其实定义在objcet中。这也就说明 java中所有的对象都是可以比较大小(具体的比较规则都在各自的子类中重写了)。

protected void finalize()
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
手动管理内存的方法。java一般不需要自己来管理内存(垃圾回收器会自动回收),但是在JIN调用C语言的方法的时候可能需要自己来管理内存 内存的回收就在这个方法来写的。

Class getClass()
Returns the runtime class of this Object.
返回 运行时对象的类。

String toString()
Returns a string representation of the object.
返回代表这个对象的字符串。

equals的简单使用

/ 所有类都继承直 Object
// Object类的方法 所有的类都能使用
// 1. 父类的equal方法     boolean     equals(Object obj)
class Demo {
    private int num;
    public Demo(int num) {
        this.num = num;
    }
    // 覆盖父类方法
    @Override
    public boolean equals(Object obj) {
        /*
         *  关键字 instanceof
         *  对象是否是这个特定类或者是它的子类的一个实例。
         *  如果 object 是 class 的一个实例,则 instanceof 运算符返回 true。
         *  如果 object 不是指定类的一个实例,或者 object 是 null,则返回 false。 
         */
        if(!(obj instanceof Demo))
            return false;
        // 向下转型
        Demo d = (Demo)obj;
        return this.num == d.num;
    }

}

public class objectDemo {
    public static void main(String[] args) {
        Demo d1 = new Demo(4);
        Demo d2 = new Demo(6);
        // Object默认比较的是地址
        // 此处复写 父类的equals方法 比较类中数据大小
        System.out.println(d1.equals(d2));
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值