Java中包私有类的利弊? [英] Pros and cons of package private classes in Java?

查看:247
本文介绍了Java中包私有类的利弊?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近学习Java,我遇到了 package-private 类的概念,如果我们不指定任何内容,这是默认的。但后来我意识到:


  1. 我很少看到package-private类的使用。有这样的原因,例如,它有严重的缺点,它是多余的,或者只是我不足够?


  2. 如果在大多数情况下它真的无用,为什么会是默认的?

    / li>
  3. 在现实世界中我们应该在什么情况下使用package-private?


换句话说,默认包的主要优点和缺点是什么? - 私人修改者?

解决方案

简短的答案是 - 这是一种略宽的私人形式。



我假设你熟悉 public private 之间的区别,以及为什么通常的好习惯是使方法和变量 private ,如果它们只在内部使用的话。



好吧,作为一个扩展,如果你正在考虑以模块化方式创建你的软件,你可能会考虑一个公共接口到你的模块,它将有多个在它里面的类在它们之间协作。在这种情况下,使得方法 public 如果他们将被消费者调用是非常有意义的; private 如果它们是类的内部;和 package private ,如果它们用于在这个模块中的类之间调用,即它是你的模块的实现细节(如公共调用者看到的),但跨越几个类。 / p>

这在实践中很少使用,因为软件包系统对这种事情不太有用。你必须将给定模块的所有类转储到完全相同的包中,这对于任何不重要的将会有点笨重。所以这个想法是伟大的 - 使一个方法可以访问只是一小部分附近类,作为一个略宽的 private - 但是如何定义该组类的限制意味着它很少使用/有用。


I am learning Java recently, and I came across the notion of package-private classes, which is the default if we don't specify anything. But then I realized:

  1. I seldom see the use of package-private class. Is there a reason for this, e.g., it has serious drawbacks, it is redundant, or simply I am not reading enough? Are there strong arguments for/against its usage?

  2. If it is really not useful in most cases, why would it be the default?

  3. In what situation should we use package-private in the real world? I.e., when would it become irreplaceable?

In other words, what are the major pros and cons of the default package-private modifier?

解决方案

The short answer is - it's a slightly wider form of private.

I'll assume that you're familiar with the distinction between public and private, and why it's generally good practice to make methods and variables private if they're going to be used solely internally to the class in question.

Well, as an extension to that - if you're thinking about creating your software in a modular way, you might think about a public interface to your module, which will have multiple classes inside it collaborating between themselves. In this context it makes perfect sense to make methods public if they're going to be called by consumers; private if they're internal to a class; and package private if they're used to call between classes in this module, i.e. it's an implementation detail of your module (as seen by public callers) but spans several classes.

This is seldom used in practice, because the package system turns out to not be so useful for this sort of thing. You'd have to dump all of the classes for a given module into exactly the same package, which for anything non-trivial is going to get a bit unwieldy. So the idea is great - make a method accessible to just a handful of "nearby" classes, as a slightly wider private - but the restrictions on how you define that set of classes means it's rarely used/useful.

这篇关于Java中包私有类的利弊?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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