为什么Java中的Object类包含受保护的方法? [英] Why does the Object class in Java contain protected methods?

查看:137
本文介绍了为什么Java中的Object类包含受保护的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么对象类在Java中包含受保护的方法,例如 clone() finalize() ,如果您使用或编写的所有类都继承了Object的实例方法?

Why does the Object class in Java contain protected methods, such as clone() and finalize(), if all classes you use or write inherit the instance methods of Object?

推荐答案

如果类 C2 扩展 C1 C1 包含 public 方法,然后是 C2 <中的方法/ code>(如果被覆盖)也必须是 public ; Java在覆盖时对方法的访问施加额外限制是非法的。如果 C1 包含 protected 方法,则 C2 可能受保护 public

If class C2 extends C1, and C1 contains a public method, then the method in C2 (if overridden) must also be public; Java makes it illegal to put additional restrictions on a method's access when overriding. If C1 contains a protected method, then an overriding method in C2 may be protected or public.

即使 C1 对象,这些规则也适用类。
所以我认为原因是类(所有继承自 Object )都可以声明自己的重写 clone finalize 方法并使它们 protected 如果他们选择,而不是 public

These rules apply even if C1 is the Object class. So I think the reason is so that classes (which all inherit from Object) can declare their own overriding clone and finalize methods and make them protected if they choose, instead of public.

编辑:这样做的一个重要结果是克隆 finalize 不像公共成员那样可以自由访问。在类 C2 中,您可以使用 clone finalize 一个类型为 C2 的对象,因为它们是受保护的方法,因此可用于子类 C2 。但是你不一定能在另一个类的对象上使用它们。

An important consequence of this is that clone and finalize are not as freely accessible as a public member would be. Within class C2, you can use clone and finalize on an object of type C2 all you want, since they are protected methods and therefore available to the subclass C2. But you can't necessarily use them on objects of another class.

class X { }

class Y {
    private Y field1;
    private X field2;
    public void foo() throws Exception {
        Object o1 = this.clone();      // legal
        Object o2 = field1.clone();    // legal
        Object o3 = field2.clone();    // illegal
        String s1 = field2.toString(); // legal since toString() is "public" in Object
    }
}

这应该证明虽然子类可以访问 protected 方法,但是对它们的可访问性仍有一些限制。请注意,如果 X 具有 @Override公共对象clone()方法,则声明 o3 将合法化。

This should demonstrate that although protected methods are accessible to subclasses, there are still some restrictions on how accessible they are. Note that if X had an @Override public Object clone() method, then the declaration of o3 would become legal.

这篇关于为什么Java中的Object类包含受保护的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆