学习java,为什么我的隐私是私有的?

发布于 2024-11-19 17:49:22 字数 232 浏览 4 评论 0原文

我正在学习java,来自python,有很多我不完全理解java中存在的东西,其中第一个必须是公共和私有声明。我的意思是,从一种没有真正可见的公共私有声明的语言到一种一切都必须是私有的语言,我理解它们所做的基本原则。我问他们“为什么”这样做。为什么有人要关心谁触摸了隐私部位?如果你是一个优秀的程序员,你知道你“应该”和“不应该”在代码中插入哪些部分,那么这应该不是问题。那么为什么要保密呢?为什么要隐藏、遮盖并使事情不被世界所知?为什么要关心开始。

Im learning java, coming from python there are quite a few things I don't fully understand that exist in java and the first of these has to be public and private declarations. I mean from a language that has no real visible public private declarations to a language where everything MUST be private, I understand the ground principle about what they do. Im asking 'why' they do it. Why should anyone care who touches there private parts? It shouldn't really be a problem if your a good programmer you know which bits you 'should' and 'should not' poke in code. So why the secrecy? Why hide and obscure and make things private from the world? Why care to start with.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

北城挽邺 2024-11-26 17:49:23

您不希望其他程序员访问并可能修改您的私有变量。例如

private int ryan; //its your responsibility to save private ryan

,抛开所有笑话,私有变量对于封装很有用。另外,私有构造函数不允许子类化和工厂方法模式中的功能。具有私有构造函数的类只允许在该类中实例化对象(例如可以通过静态公共方法来完成)。

正如您所看到的,私有变量非常有用......

You don't want other programmers accessing and possibly modifying your private variables. e.g.

private int ryan; //its your responsibility to save private ryan

All jokes aside, privates are useful for encapsulation. Plus, private constructors disallow subclassing and feature in the factory method pattern. Classes with private constructors only allow objects to be instantiated within this class (which can be done via a static public method for example).

So as you can see, privates can be quite useful....

寂寞美少年 2024-11-26 17:49:23

这种隐藏数据成员的原则称为数据封装

从上面的文章:

使用数据封装的优势出现在以下情况:
类的实现发生变化,但接口保持不变
相同的。例如,要创建一个可以包含整数的堆栈类,
设计者可以选择用隐藏的数组来实现
来自班级的用户。然后设计者编写push()和
pop() 方法将整数放入数组并从中删除
分别为数组。这些方法可供用户访问。
如果用户尝试直接访问数组,则会出现
将导致编译时错误。现在,设计师是否应该决定
将栈的实现改为链表,数组可以
只需替换为链表以及push()和pop()方法
重写,以便它们操作链接列表而不是
大批。用户编写的用于操作堆栈的代码是
仍然有效,因为它没有直接访问数组
开始于。

This principle of hiding data members is known as Data Encapsulation.

From the article above:

The advantage of using data encapsulation comes when the
implementation of the class changes but the interface remains the
same. For example, to create a stack class which can contain integers,
the designer may choose to implement it with an array, which is hidden
from the user of the class. The designer then writes the push() and
pop() methods which puts integers into the array and removes them from
the array respectively. These methods are made accessible to the user.
Should an attempt be made by the user to access the array directly, a
compile time error will result. Now, should the designer decide to
change the stack's implementation to a linked list, the array can
simply be replaced with a linked list and the push() and pop() methods
rewritten so that they manipulate the linked list instead of the
array. The code which the user has written to manipulate the stack is
still valid because it was not given direct access to the array to
begin with.

追星践月 2024-11-26 17:49:23

您可以自由地将班级中的每个字段声明为公共字段。为什么这不被认为是“良好实践”,因为在多开发人员的情况下,代码库必须随着时间的推移(以及在您离开后)进行维护,对于其他人来说能够理解您的类(以及如何理解您的类)非常重要。它们应该或不应该被使用)。将字段设置为“私有”是一种很好的方法,可以强制表明该字段是类内部的工作方式,不应从外部进行修改。这不是关于“模糊”,而是关于“保护”和“维护”(请参阅​​上面有关 API 和合约的帖子)。

当然,如果有足够的时间,“优秀的程序员”最终能够弄清楚代码的确切工作原理 - 但为什么你不节省他或她的时间,而只努力公开“公共”功能( API)并隐藏不应该接触的东西?

顺便说一句,纯粹为了您的利益,不实行适当的数据封装和 API/公共接口纪律将使您的同事讨厌您,并且很可能会在短时间内解雇您。您生成的代码将被视为(正确地)非常脆弱且难以维护。

You are free to declare every field in your class as public. Why this is not considered "good practice" is because in a multi-developer situation, where a codebase has to be maintainable over time (and after you leave), it is important for other people to be able to understand your classes (and how they should and should not be used). Making a field "private" is an excellent way to forcible indicate that this field is internal to the workings of the class and should not be modified from the outside. It's not about "obscuring", it's about "securing" and "maintaining" (see above posts about API and contract).

Sure, a "good programmer" would be able to eventually figure out the exact workings of your code, given enough time - but why would you not spare him or her that time by instead making the effort of only exposing the "public" functionality (the API) and hiding the stuff that should not be touched?

On a side-note, and purely for your benefit, not practicing proper data encapsulation and API/public interface discipline will make your peers detest you and will most likely get you fired, in short order. The code you produce will be regarded (rightly) as very brittle and unmaintainable.

半窗疏影 2024-11-26 17:49:23

以此为例说明为什么您可能希望阻止其他程序员甚至您自己直接使用变量。

class Car() {
    public int speed;
}

您或其他程序员可能只是执行“speed = -20”(可能是因为计算错误或另一个函数未按预期运行)。然后,当你尝试使用你的速度时,你会得到奇怪的结果,并花费时间和精力来追踪问题。这是一个更好的解决方案:

class Car() {
    private int speed;

    public void setSpeed(int newSpeed) {
        if (newSpeed < 0)
            throw new Exception("Car speeds can't be negative!");
        speed = newSpeed;
    }

    public int getSpeed() {
        return speed;
    }
}

您将立即知道您的界面是否被非预期地使用。

您的问题表明您可能对为什么公共和私有方法有用感到有点困惑,所以让我们退后一步。

您不会将“所有内容”声明为私有。当你不希望其他类使用它们时,你可以将它们声明为私有——它们完全供内部使用。当使用您的类需要调用该方法或使用该变量时,您可以将事物声明为公共。事实上,没有公共方法的类不会那么有用! (这个说法纯粹是谎言,但它适用于我们正在讨论的内容。)

通过将您打算从类外部使用的东西设为公共,并将其他所有内容设为私有,您正在为使用您的类的人们创建一个接口 -无论是你还是其他人。繁重的工作对其他班级来说都是隐藏的。

用一句话来说:“针对接口编程,而不是实现。”当你编写一个类时,首先想到的应该是“我如何让其他类使用我的类?”,而不是“我应该如何获得我想要的功能?”在我看来,这种区别就是进行命令式编程和面向对象编程时应具备的思维方式之间的差异。

Take this example of why you might want to prevent other programmers, or even yourself, from using a variable directly.

class Car() {
    public int speed;
}

You, or another programmer, might just do "speed = -20" (perhaps because a calculation was wrong or another function isn't acting as expecting). Then when you try to use your speed, you get weird results and spend time and energy tracking down the problem. This is a better solution:

class Car() {
    private int speed;

    public void setSpeed(int newSpeed) {
        if (newSpeed < 0)
            throw new Exception("Car speeds can't be negative!");
        speed = newSpeed;
    }

    public int getSpeed() {
        return speed;
    }
}

You will know right away if your interface is used as you don't intend.

Your question indicates that you might be a little confused about why public and private methods are even useful, so let's take a step back.

You don't declare "everything" private. You declare things private when you do not want other classes using them -- they are totally for internal use. You declare things public when use of your class requires calling that method or using that variable. Indeed, a class with no public methods wouldn't be that useful! (this statement is a pure lie but it works for what we're talking about.)

By making the things you intend to be used from outside the class public and everything else private, you are creating an interface for people using your classes -- either you or others. The heavy lifting is hidden from every other class.

In one sentence: "Program to an interface, not an implementation." When you write a class, the first thought should be "How do I intend other classes to use my class?", not "How should I get the functionality I want?" In my opinion, that distinction is the difference between the mindsets you should have when doing imperative programming and object oriented programming.

因为看清所以看轻 2024-11-26 17:49:23

嗯,很容易理解 java 中对私有修饰符的需求,java 是一种纯粹的面向对象语言

,考虑到你有一辆非常漂亮的跑车 A!

您想要一个名为“gasPumped”的字段以及其他一些可以提高速度的字段吗?

或者

您想要一个名为increaseSpeed()的函数来访问所有这些字段吗?

也许当您获得这辆车的新版本时,它将具有相同的increaseSpeed(),并且可以操作更多字段!

汽车制造商希望您知道您可以

增加速度()

但他并不是真的想让你知道里面的部分!

well it is really easy to understand the need for private modifiers in java which is purely an object oriented language

consider you have a very nice sports car A!

would you like to have a field called gasPumped and maybe some other fields that may increase the speed?

or

would you like to have a function called increaseSpeed() which access all these fields?

Probably when you get the new version of this car, it will have the same increaseSpeed() with much more fields that are manipulated!

The car manufacturer wants you to know that you can

increaseSpeed()

but he doesnt really want you to know the inside parts!

枕头说它不想醒 2024-11-26 17:49:23

我想说 Java 中的私有是私有的,因为:

  • 该机制是从 C++ 继承的(在 C++ 中,让客户端可以访问所有字段/方法意味着将它们放在头文件中,这会给客户端带来重大且过度的负担)
  • 它允许进行一些原本不可能的静态优化(例如,您可以内联私有方法调用 - 有效地从编译的类中删除该方法,同时仍然保持源代码的结构化)。

I would say that privates are private in Java because:

  • the mechanism is inherited from C++ (in C++, having all fields/methods be accessible by clients would mean putting them in the header file, which would put a significant and undue burden on the clients)
  • it allows for some static optimizations that are otherwise impossible (e.g. you can inline a private method call - effectively removing the method from the compiled class, while still keeping your source code structured).
青衫负雪 2024-11-26 17:49:23
  • 它简化了 API,以保持依赖于实现的内容的私有性。
  • 良好的面向对象设计要求每个类都有自己的功能范围。因此,防止其他人通过直接访问这些字段或依赖于实现的方法来违反这一点是一件好事。
  • 通过这种方式,类更容易维护。例如,更改内部数据结构不会影响其他人直接访问字段时的情况。
  • 其他人不能弄乱对象的状态。
  • It simplifies the API to keep implementation dependent stuff private.
  • Good object oriented design demands that each class has its own scope of functionality. Hence its a good thing to keep others from violating this by accessing such fields or implementation dependent methods directly.
  • Classes are easier to maintain this way. For example changing the internal data structure doesn't affect others which would be the case when they accessed the fields directly.
  • Other people can't mess up the object's state.
樱娆 2024-11-26 17:49:22

(固执己见的答案如下。)

这是因为 Java 是一种束缚和纪律语言,旨在迎合对于平庸程序员。 Python,otoh,是一种针对同意的成年人的语言同意彼此公开其对象的私有部分,相信其他程序员不会滥用提供给他们的未记录/未保证的功能。如果他们这样做并且有任何东西损坏,则损坏东西的人可以保留碎片。

Python确实有一些访问控制,例如 __all__ 隐藏/显示模块的某些部分,只是所有这些都是可选的,并且可以绕过这样做的人的风险。

(重复我在评论中所说的话:我并不是说所有 Java 程序员都是平庸的。我只是说该语言的设计是为了让这些程序员可以安全地使用它。 )

(Opinionated answer follows.)

This is because Java is a bondage and discipline language, designed to cater for mediocre programmers. Python, otoh, is a language aimed at consenting adults who agree to expose their objects' private parts to each other, trusting other programmers not to abuse the undocumented/unguaranteed functionality offered to them. If they do and anything breaks, the person who broke stuff gets to keep the pieces.

Python does have some access control, such as __all__ to hide/show parts of a module, it's just that all of it is optional and can be by-passed at the risk of the person doing so.

(To repeat what I said in the comment: I'm not saying that all Java programmers are mediocre. I'm just saying that the language is designed so that it can safely be used by such programmers.)

第七度阳光i 2024-11-26 17:49:22

因为其他人不像你那么关心你的私处。您决定什么是私人的,什么不是私人的。

严肃地说,公共事物定义了 API——与外界的契约——这是一个重要的决定。另一方面,尽可能多的东西应该是私有的——这就是封装。欢迎来到 OO。

Because others people don't care nearly as much about your privates as you do. You decide what is and isn't private.

On a serious note, public things define the API - the contract with the outside world - it's an important decision to make. On the other hand, as much stuff as possible should be private - that's encapsulation. Welcome to OO.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文