与Java封装概念混淆 [英] Confused with Java Encapsulation Concept

查看:59
本文介绍了与Java封装概念混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天!

我正在阅读一本有关封装的Java书,其中提到了getter和setter方法。

I am reading a Java book about encapsulation and it mentioned the getter and setter method.

我已经读过要隐藏属性,我必须将实例变量标记为 PRIVATE ,并使 PUBLIC 方法为 getter和setter 访问数据。因此,我尝试按以下方式制作类似但非常规的代码:

I've read that to hide the attributes, I must mark my instance variables as "PRIVATE" and make a "PUBLIC" method of getter and setter to access the data. So I tried making a similar but not the conventional code about it as follows:

public class AddressBookEntry {

    private String name;
    private String address;
    private String telNo;
    private String email;

    public void getAllInfo() {
        name = JOptionPane.showInputDialog("Enter Name: ");
        address = JOptionPane.showInputDialog("Enter Address: ");
        telNo = JOptionPane.showInputDialog("Enter Tel. No: ");
        email = JOptionPane.showInputDialog("Enter Email Address: ");
    }
}

上面的代码是否公开了我的变量,因为我分配了它直?我该如何做得更好?如果改用常规的 getter和setter 方法并在另一个类上分配值,会更好吗? 隐藏数据是什么意思?

Does my code above exposes my variables because I assigned it directly? How can I do this better? Would it be better if I make the conventional getter and setter method instead and assigned the values on the other class? What does "hiding the data" means?

谢谢。

推荐答案

是的,不是。封装的要点是,它可以防止其他类需要知道您的类在后台做什么。如果将名称存储在 String 中(如此处所述),请从文件中读取/写入它或执行其他操作时,封装的重点是对您的类的用户而言无关紧要,因为所有他们看到的都是 String getName() void setName(字符串名称)

Yes and no. The point of encapsulation is that it prevents other classes from needing to know what your class is doing behind the scenes. If you store your name in a String (as you've done here), read/write it from a file, or do something different, the point of encapsulation is that to the user of your class it doesn't matter because all they see is String getName( ) and void setName (String name).

由于数据的修改完全在您的课程在这里,它不会破坏封装。如果您没有名称存储到文件中,则可以在 getAllInfo 中这样做,而无需该类的任何其他用户都是明智的。由于该类的外部的可观察到的行为仍然隐藏了该类的内部操作,因此仍被封装。

Since the modification of the data is entirely under the control of your class here, it doesn't break encapsulation. If you did store name to file, then you could potentially do so in getAllInfo without any other user of the class being any the wiser. Since the observable behaviour from the outside of the class still hides what the internals of the class is doing, it's still encapsulated.

这是一种非常常规的方法。就像我在第一段中描述的那样,使用访问器方法(getter和setter)是一种更惯用的方法,对于使用您的代码的其他人来说更容易理解。您可以做您想做的事情,它不会破坏封装,但这不是我所说的优雅或典型。

That said, this is a very unconventional approach. Like I describe in the first paragraph, use of accessor methods (getters and setters) is a more idiomatic approach, and easier to understand for someone else using your code. You can do what you do, it doesn't break encapsulation, but it's not what I'd call elegant or typical.

这篇关于与Java封装概念混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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