JAVA - 初学者 - 可以在类外访问私有类属性吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12196185/
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-10-31 07:59:58  来源:igfitidea点击:

JAVA - Beginner - Can a private class attribute be accessed outside of the class?

javaprivate-class

提问by AlexM

I am relatively new to Java OO Programming, and have reviewed the questions similar to this, although they don't seem to answer my question directly.

我对 Java OO Programming 比较陌生,并且已经查看了与此类似的问题,尽管它们似乎没有直接回答我的问题。

Basically, I understand that if a data member within a class is declared as private, then it is only accessible from within that same class.

基本上,我明白如果一个类中的数据成员被声明为private,那么它只能从同一个类中访问。

My lecturer always advises that ALL attributes should be declared as private - why is this?

我的讲师总是建议所有属性都应该声明为私有的 -为什么会这样?

Now I am familiar with using GET methods, and my question is, can a private attribute be accessed outside of it's own class via invoking a PUBLIC 'get' method (which returns the aforementioned attribute) from another class?

现在我熟悉使用 GET 方法,我的问题是,是否可以通过从另一个类调用 PUBLIC 'get' 方法(返回上述属性)在它自己的类之外访问私有属性?

For example:

例如:

public class Class()
{

    private int number = 0;

    public Class()
    {
    }

    public int getNumber()
    {
        return number;
    }

}

And then from another class:

然后从另一个类:

public class Class2()
{

    Class class = new Class();

    public void showNumber()
    {
        System.out.print(class.getNumber());
    }
}

Will the second block of code allow the method in showInt()inside Class2 to actually access the private attribute from Class?

第二个代码块是否允许Class2中的showInt() 中的方法实际访问 Class 中的私有属性?

I guess I am really struggling with deciding whether any attribute or method should be declared publicor privatein general..

我想我真的很难决定是否应该将任何属性或方法声明为公共私有

Is there any particular rule of thumb that should be followed?

是否有任何特定的经验法则应该遵循?

Thank you responders for any assistance.

感谢响应者的任何帮助。

Kind regards

亲切的问候

采纳答案by Marko Topolnik

The key point is that a public getmethod only returns the current valueof your private member, without giving access to the member itself. This means that you cannot somehow "get" the member and change its value.

关键是公共get方法只返回私有成员的当前值,而没有授予对成员本身的访问权限。这意味着您无法以某种方式“获取”成员并更改其值。

回答by Peter Lawrey

My lecturer always advises that ALL attributes should be declared as private.

我的讲师总是建议所有属性都应该声明为私有。

Good advise. There are exceptions to this rule but I would start with this.

好建议。这个规则有例外,但我会从这个开始。

I understand that if a data member within a class is declared as private, then it is only accessible from within that same class.

我知道如果一个类中的数据成员被声明为私有,那么它只能从同一个类中访问。

Its accessible to

它可以访问

  • nested classes in the same file.
  • access via reflection.
  • 同一个文件中的嵌套类。
  • 通过反射访问。

Will the second block of code allow the method in showInt() inside Class2 to actually access the private attribute from Class?

第二个代码块是否允许 Class2 中的 showInt() 中的方法实际访问 Class 中的私有属性?

Effectively yes in this case. With the use of a getter, the field can change name, be replaced by a constant or a calculation or be logged and Class2 doesn't need to know.

在这种情况下是有效的。通过使用 getter,该字段可以更改名称、被常量或计算替换或被记录,而 Class2 不需要知道。

回答by Denys Séguret

Yes, if you make a public accessor, you may access the private field.

是的,如果您创建公共访问器,则可以访问私有字段。

The point is to hide the implementation so that, as an implementor, you may decide later to have another type of field (or an indirection, or a dynamic computation) without forcing the users of your class to change their code.

关键是隐藏实现,以便作为实现者,您可以稍后决定使用另一种类型的字段(或间接或动态计算),而无需强迫您的类的用户更改他们的代码。

It also lets you offer a getter while not offering any setter (then your field is read only from outside the class).

它还允许您提供一个 getter 而不提供任何 setter(然后您的字段只能从类外部读取)。

Many things wouldn't compile in your code :

许多事情不会在您的代码中编译:

  • add parenthesis to call a method (getInt)
  • class is a reserved word
  • a class can't be called Class and isn't declared as you did
  • 添加括号以调用方法(getInt)
  • 类是保留字
  • 一个类不能被称为 Class 并且没有像你那样声明

I'd suggest you write a compiling code in an editor (e.g. Eclipse) before asking a question. This task would probably help you understand at least part of the problems.

我建议您在提问之前在编辑器(例如 Eclipse)中编写编译代码。此任务可能至少会帮助您了解部分问题。

回答by Bart Friederichs

Yes.

是的。

You will have to call the method though (and you cannot use classas a class name):

不过,您必须调用该方法(并且不能class用作类名):

public class Class2()
{

    Class myClass = new Class();

    public void showInt()
    {
        System.out.print(myClass.getInt());
    }
}

What happens is that you do not get access to the private member, but you receive a copy of the value. In this case, you access the method getInt(), and not the attribute. If you would try to access the attribute:

发生的情况是您无法访问私有成员,但您会收到该值的副本。在这种情况下,您访问的是 getInt() 方法,而不是属性。如果您尝试访问该属性:

public class Class2()
{

    Class myClass = new Class();

    public void showInt()
    {
        System.out.print(myClass.x);
    }
}

you will not be given access.

您将无法获得访问权限。

回答by Dylan

Short answer: no.

简短的回答:没有。

The general reason for making everything private is to make sure that users of your class can't modify things in ways they aren't supposed to.

将所有内容设为私有的一般原因是确保您的类的用户无法以他们不应该的方式修改内容。

What you cando is define getter and setter methods. Generally it's best to only expose getters, e.g.

可以做的是定义 getter 和 setter 方法。通常最好只暴露吸气剂,例如

private int foo;

public int getFoo(){
  return foo;
}

This way, people can seefoobut not change it.

这样,人们可以看到foo但不能改变它。