为什么java中的Object类中有公共方法?
当我们知道在 java 中所有类默认扩展了 Object 类时,为什么有带有 public 修饰符的方法,而 protected 足以从任何类访问这些方法呢?所以需要一些这方面的信息。 谢谢。
When we know that in java all classes by default extends Object class, so why there are methods with public modifier where as protected would suffice the accessing of these methods from any class? So need some info on this.
thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果对象方法不是公共的(或包范围的),则无法从子对象外部调用它们。它们被所有 Java 对象继承的事实与这些方法的范围是正交的。
简单的例子:您多久调用一次
x.toString()
?如果该方法不是公开的,你就无法做到这一点。如果该方法根本不存在于 Object 中,则必须为每个新类重新实现它。If Object methods weren't public (or package-scoped), you couldn't call them from outside the child object. The fact that they are inherited by all Java objects is orthogonal to the scoping of these methods.
Quick example: how often do you call
x.toString()
? You couldn't do that if that method weren't public. And if that method didn't exist in Object at all, you'd have to re-implement it for every new class.clone()
是 Object 上的受保护方法,您无法在其他类的实例上调用clone()
。clone()
is a protected method on Object and you can't callclone()
on instances of other classes.来自任何类,是的,但不能在任何
Object
上:Java 语言规范 定义
protected
的含义如下:也就是说,子类 S 只能在 S 的实例上调用超类 C 的受保护构造函数/成员。
From any class, yes, but not on any
Object
:The Java Language Spec defines the meaning of
protected
as follows:That is, a subclass S may invoke protected constructors/members of a super class C only on instances of S.
<编辑>
尽管一个对象可以访问同一类的所有对象的私有属性,但您无法从其他类访问该对象的受保护方法,即使该受保护方法是在公共超类中定义的。
因此,当此代码编译时:
以下代码将不会编译:
能够对所有对象调用
toString()
、equals(Object)
、hashCode()
和getClass() 使事情变得简单容易得多。
clone()
和finalize()
受到保护。因此,为了能够从外部调用它们,子类必须增加可见性。这显然是一个设计决定。说实话,我不知道为什么Sun决定所有对象都是“锁”并且有
。从我的角度来看,这些方法根本不应该在 Object 中,而应该在专门的 Lock 类中。但我想在很早的时候就有充分的理由让它们存在,现在不能在不破坏兼容性的情况下改变它。notify()
,notifyAll()
,wait(长)
,等待(长,int)<Edit>
Although one object can access private properties of all objects of the same class, you cannot access protected methods of an object from other class even if the protected method is defined in a common super class.
So while this code compiles:
The following code will not compile:
</Edit>
Being able to call
toString()
,equals(Object)
,hashCode()
andgetClass() on all objects makes things a lot easier.
clone()
andfinalize()
are protected. So in order to be able to call them from the outside the subclass has to increase the visibility. And that is obviously a design decision.To be honest, i have no idea why Sun decided that all object are "locks" and have
. From my point of view those method should not be in Object at all but in a specialized Lock-class. But I guess there was a good reason to have them there in the very early days and it cannot be changed nowadays without breaking compatibility.notify()
,notifyAll()
,wait(long)
, wait(long, int)