第04周 预习、实验与作业:类的设计与继承

一.为什么说Java中的所有类都is-a Object?

在Java中,Object 类是所有其他类的祖先,Java中的每个类,都是从object类间接或者直接传承而来的。

二.在JDK文档中查找Object的toString方法。说一说,该方法有什么用?使用Eclipse查看Object的toString方法的代码,结合代码说说该代码的用途。

(1)在JDK文档中,Object 类的 toString 方法是一个非常重要的方法,它的主要作用是返回一个表示该对象的字符串。

public class Object {
    /**
     * Returns a string representation of the object. In general, the
     * {@code toString} method returns a string that
     * "textually represents" this object. The result should
     * be a concise but informative representation that is easy for a
     * person to read.
     * It is recommended that all subclasses override this method.
     * <p>
     * The {@code toString} method for class {@code Object}
     * returns a string consisting of the name of the class of which the
     * object is an instance, the at-sign character `{@code @}', and
     * the unsigned hexadecimal representation of the hash code of the
     * object. In other words, this method returns a string equal to the
     * value of:
     * <blockquote>
     * <pre>
     * getClass().getName() + '@' + Integer.toHexString(hashCode())
     * </pre></blockquote>
     *
     * @return  a string representation of the object.
     */
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
}

(2) 关于这段代码中,相应的代码解释是:
getClass().getName():获取对象的类的全限定名。
hashCode():返回对象的哈希码。
Integer.toHexString(hashCode()):将哈希码转换为十六进制字符串。
这样可以更好的理解Object的toString方法的使用。

三.在IDE中查看Object的equals方法的代码,说说equals的用途。该方法被什么修饰符修饰,意味着什么?什么时候需要覆盖equals方法?结合String类的equals方法说说覆盖如何体现子类特有的特性?

(1)equals 方法用于比较两个对象是否相等,这样基于对象引用的比较。
(2)equals中的public修饰,其中equals 方法是公共的,可以被任何类访问。boolean:方法返回一个布尔值,表示两个对象是否相等。
Object obj:方法参数是一个 Object 类型的对象,表示要与当前对象进行比较的对象。
(3)当需要根据对象的内容而不是引用来进行比较时,此时就需要覆盖 equals 方法。

四.如果在子类中想要复用父类的代码,要怎么办?

(1) 使用 super 关键字
super 关键字可以用来调用父类的方法或访问父类的成员变量。这是最直接的方式,适用于方法覆盖和成员变量访问。
(2) 使用模板方法模式
模板方法模式是一种设计模式,它定义了一个算法的骨架,而将一些步骤延迟到子类中实现。子类可以重写这些步骤,但不改变算法的结构。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值