Java 为什么在私有类中有公共方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18868462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:46:24  来源:igfitidea点击:

Why have public methods inside private classes?

java

提问by Somjit

I was going through a part of a code which was something like this

我正在经历一段类似这样的代码

// compare points according to their polar radius
public static final Comparator<Point2D> R_ORDER = new ROrder();
.
.
.
private static class ROrder implements Comparator<Point2D> {
    public int compare(Point2D p, Point2D q) {
        double delta = (p.x*p.x + p.y*p.y) - (q.x*q.x + q.y*q.y);
        if (delta < 0) return -1;
        if (delta > 0) return +1;
        return 0;
    }
}

Why do we have such public methods inside private static classes. What harm would it do if i made ROrder

为什么我们在私有静态类中有这样的公共方法。如果我制作了 ROrder 会有什么危害

  1. Non-Static
  2. Public
  1. 非静电
  2. 民众

采纳答案by Narendra Pathai

ROrderNon-Static

ROrder非静电

By making it non-staticyou will need the instance of the container class to create the instance of ROder, which maybe due to the design of the class would not make logic. You should keep class non-static only when you really need the instance of outer class to get the instance of inner class.

通过制作它,non-static您将需要容器类的实例来创建 的实例ROder,这可能是由于类的设计不会产生逻辑。只有当您确实需要外部类的实例来获取内部类的实例时,才应该保持类非静态。

ROrderPublic

ROrder民众

Again because they wanted to restrict the use of ROrderoutside the context of this class. They did not want any client code or other code to freely create instances of ROrder, as they would not be of any use.

再次是因为他们想限制在ROrder这个类的上下文之外使用。他们不希望任何客户端代码或其他代码自由创建 的实例ROrder,因为它们没有任何用处。

Why do we have such public methods inside private static classes.

为什么我们在私有静态类中有这样的公共方法。

In this case because you are implementing an interfaceComparatorand you will pass this comparator for other uses, such as sorting and you would want the Collectionsclass to have the visibility of comparemethod, so the method has to be publiceven if the class implementing the interface is private.

在这种情况下,因为您正在实现 aninterfaceComparator并且您将传递此比较器用于其他用途,例如排序,并且您希望Collections该类具有compare方法的可见性,因此该方法必须是public即使实现接口的类是private.

So this is just a logical way to enhance the readabilityand intent of useof the code.

所以这只是一种增强代码可读性使用意图的合乎逻辑的方式。

Logical Use

逻辑使用

This class wants the string to be in some format.

此类希望字符串采用某种格式。

public class SomeClass{

     private static class StringHelper{
          //will do the task of parsing and validating that string object
     } 
}

Now in this case you would not want to keep StringHelperclass public, as its use is too localized to be reused. So you would rather emphasize that by keeping it private. And there can be methods that are publicif StringHelperimplemented some interface.

现在在这种情况下,您不想保留StringHelperclass public,因为它的使用过于本地化而无法重用。所以你宁愿通过保留它来强调这一点private。并且可以有一些方法,public如果StringHelper实现了某个接口。

UPDATE:

更新:

You should keep class non-static only when you really need the instance of outer class to get the instance of inner class.

只有当您确实需要外部类的实例来获取内部类的实例时,才应该保持类非静态。

On that I think the answer can be too broad, but I would try to explain in short. By that what I mean was that if the inner class object shares some state of the outer objecton which its processing is dependent, then you will need the object of outer class to share its state with the inner class object, but if the inner class instance is independent of the state of outer class, then it is safe to keep the inner class static.

对此,我认为答案可能过于宽泛,但我会尽量简短地解释一下。我的意思是,如果内部类对象共享其处理所依赖的外部对象的某些状态,那么您将需要外部类的对象与内部类对象共享其状态,但是如果内部类实例独立于外部类的状态,那么保留内部类是安全的static

回答by Bohemian

All private members (fields, classes, whatever) are only visible inside the class. So, it doesn't matter what visibility you give a method of a private class - all methods will only be visible inside the containing class, because the class itself is private.

所有私有成员(字段、类等)仅在类内部可见。因此,您为私有类的方法提供什么可见性并不重要 - 所有方法仅在包含类中可见,因为类本身是私有的。

If the inner class implements an interface or extends a class, overridden methods may not have less visibility than the declaration in the super type, so that's one reason to have public methods in a private inner class.

如果内部类实现了一个接口或扩展了一个类,被覆盖的方法的可见性可能不会低于超类型中的声明,所以这是在私有内部类中拥有公共方法的原因之一。

However, although the syntax allowsprivate classes to have public methods, it won't increase the visibility of those methods sufficiently to be visible outside the containing class. There are several examples in java of modifiers being legal but having no effect, such as inner interfaces being implicitly static (whether or not the static keyword is used).

然而,尽管语法允许私有类具有公共方法,但它不会将这些方法的可见性提高到足以在包含类之外可见。java中有几个修饰符合法但无效的例子,例如内部接口是隐式静态的(无论是否使用static关键字)。

回答by Sean Owen

This class implements Comparatorand so must implement its methods. The implementation methods can't be static. Also, since interface methods are implicitly public, they must be declared public, regardless of the containing class's visibility. Try not doing so and it will fail to compile. This is certainly the reason it is declared publichere -- it can't not be.

此类实现Comparator,因此必须实现其方法。实现方法不能static。此外,由于接口方法是隐式的public,因此public无论包含类的可见性如何,都必须声明它们。尽量不要这样做,它将无法编译。这当然是它public在这里声明的原因——它不可能不是。

This is true regardless of whether the containing class is staticor public. Here, it could be either of those things and the method inside would still have to be publicand non-static.

无论包含类是static还是 ,这都是正确的public。在这里,它可以是这些东西中的任何一个,并且里面的方法仍然必须是public和非static

Other methods that don't implement an interface could be private, and, logically probably should inside a privateclass as there would be no point in declaring it otherwise -- but it would be allowed by Java syntax.

其他不实现接口的方法可能是private,并且,逻辑上可能应该在一个private类中,因为否则声明它是没有意义的——但 Java 语法允许这样做。

回答by Jerome

This class is private because developer did not want to ROrder be instantiated in other place. But an instance can be accessed through the constant R_ORDERfrom other classes.

这个类是私有的,因为开发人员不想在其他地方实例化 ROrder。但是可以通过R_ORDER其他类的常量访问实例。

The method is public for two reason : first, compareis defined in the Comparatorinterface. Second, as R_ORDER is accessible from other classes, it is more than convenient to be able to call a method on this object. In this case, it is compare.

该方法是公共的有两个原因:首先,compareComparator接口中定义。其次,由于 R_ORDER 可从其他类访问,因此能够在此对象上调用方法非常方便。在这种情况下,它是compare

Finally, if the class was not static, it would keep a reference to the parent class, which is almost always not needed

最后,如果类不是静态的,它将保留对父类的引用,这几乎总是不需要的