为什么java.lang.Object中的finalize()方法“受保护”? [英] Why is the finalize() method in java.lang.Object "protected"?

查看:197
本文介绍了为什么java.lang.Object中的finalize()方法“受保护”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于好奇,

为什么 finalize()方法的访问修饰符被设为保护。为什么不能 public ?有人可以解释一下这背后的具体原因吗?

Why is the finalize() method's access modifier is made as protected. Why cant it be public? Can someone explain me any specific reason behind this?

另外,我发现 finalize()方法是只召唤一次。如果我在程序内部调用它两次,会发生什么?垃圾收集器会再次调用它吗?

Also, I came to know that finalize() method is called only once. If I call it twice in my program internally, what is happening? Will the garbage collector call this again?

private void dummyCall() {
    try {
        finalize();
        finalize();
    } catch (Throwable e) {
        e.printStackTrace();//NOT REACHES EXCEPTION
    }
}


推荐答案

我用另一个问题回答你的问题:

I answer your question with another question:


为什么 finalize 方法不受保护?

一般来说,你应该尽量保持私密性。这就是封装的全部内容。否则,您可以所有 public finalize 不能 private (因为派生类应该能够访问它以便能够覆盖它),所以它至少应该受保护,但为什么在不可取的时候会提供更多的访问权限?

In general, you should try to keep things as much private as possible. That's what encapsulation is all about. Otherwise, you could make everything public. finalize can't be private (since derived classes should be able to access it to be able to override it), so it should at least be protected but why give out more access when it's not desirable?

在仔细阅读你的评论之后,我想我现在看到了你的要点。我认为你的观点是,因为一切都来自 java.lang.Object 并因此访问其受保护的成员,它不会'为它做任何区别(或 java.lang.Object 中的任何方法)为 public as反对 protected 。就个人而言,我认为这是Java中的一个设计缺陷。这确实在C#中得到了修复。问题不是为什么 finalize 受到保护。没关系。真正的问题是您不能通过基类类型的对象引用来调用基类中的受保护方法。 Eric Lippert有一个博客条目讨论为什么允许这种对受保护成员的访问是一个坏主意在这个问题中进一步详细阐述了Stack Overflow

After reading your comment more carefully, I guess I see your main point now. I think your point is since everything derives from java.lang.Object and consequently accesses its protected members, it wouldn't make any difference for it (or any method in java.lang.Object for that matter) to be public as opposed to protected. Personally, I'd count this as a design flaw in Java. This is indeed fixed in C#. The problem is not why finalize is protected. That's OK. The real issue is that you shouldn't be able to call protected methods in the base class through an object reference of the base class type. Eric Lippert has a blog entry discussing why allowing such kind of access to protected members is a bad idea which is further elaborated on Stack Overflow in this question.

这篇关于为什么java.lang.Object中的finalize()方法“受保护”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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