在java中将方法设为public/private/other是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2647289/
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
What does it mean for a method to be public/private/other in java?
提问by David
What does it mean for a method to be public/private/other in java?
What are the advantages and disadvantages of these options?
What is my impetus, as someone trying to be a good programmer, to care?
在java中将方法设为public/private/other是什么意思?
这些选项的优缺点是什么?
作为一个想成为一名优秀程序员的人,我关心的动力是什么?
采纳答案by OscarRyz
When a method is publicit means it can be accessed by other objects
当一个方法是公共的时,这意味着它可以被其他对象访问
For instance:
例如:
class David {
// public method, can be use by anyone
public String getName() {
return "David";
}
}
The method getName
may be accessed by other classes because it is public:
该方法getName
可以被其他类访问,因为它是公共的:
class Other {
David davidOne = new David();
String davidsName = davidOne.getName(); //<-- compiles and runs
}
The advantage.. well you can use it from other places.
优点..你可以从其他地方使用它。
When a method is privateit means it can only be accessed by objects OF THE SAME CLASS
当一个方法是私有的时,这意味着它只能被相同类的对象访问
For instance, in this new definition:
例如,在这个新定义中:
class David {
public String getName() {
return "David";
}
// private method... nobody but David's "instances" can use it..
private int getAge() {
return 19;
}
}
The method getAge
can't be accessed by other classes because it is private, if you try to do it, the compiler will give you an error message:
该方法getAge
不能被其他类访问,因为它是私有的,如果你尝试这样做,编译器会给你一个错误信息:
class Other {
David davidOne = new David();
String davidsName = davidOne.getName();
int davidsAge = davidOne.getAge(); //<-- Compiler error, getAge() is not visible
}
But, if you can use it withinDavid class:
但是,如果您可以在David 类中使用它:
class David {
public String getName() {
return "David";
}
// private method... nobody but David's "instance" can use it..
private int getAge() {
return 19;
}
// Here the call to "getAge()" will succeed, because it is visible
// inside the class
public boolean hasSameAgeAs( David otherDavid ) {
return this.getAge() == otherDavid.getAge();
}
}
The advantage? You can create a bunch of methods and keep them private, avoiding data corruption or in general preserving your objects encapsulated
优势?您可以创建一堆方法并将它们保密,避免数据损坏或通常保留封装的对象
About encapsulation
关于封装
In OOP( object oriented programming ) the intention is to model the software after real life objects.
在OOP(面向对象编程)中,目的是在现实生活对象之后对软件进行建模。
Real life objects have ( among other things ) attributes and methods to access those attributes.
现实生活中的对象具有(除其他外)属性和访问这些属性的方法。
You want to make public some of those methods, and keep private others.
您希望公开其中一些方法,而将其他方法保密。
For instance, a Humanbeing, have a heart. But it is not exposed to everybody, it would be dangerous. It is encapsulatedinside our body.
例如,一个人,有一颗心。但它不是暴露给每个人的,它会很危险。它被封装在我们的体内。
If we were to model a software after a real Humanwe may declare the method: heartBeat
as private ( so, nobody can access it )
如果我们要模仿一个真正的人类来建模一个软件,我们可以声明该方法:heartBeat
为私有的(因此,没有人可以访问它)
In the other hand, it would be useful to have come publicmethods like getGender
to find out if your Humaninstance is male or female.
另一方面,使用公共方法getGender
来确定您的Human实例是男性还是女性会很有用。
There are other access modifiers such as: "protected" and package protected ( whose doesn't have a keyword )
还有其他访问修饰符,例如:"protected" 和 package protected(没有关键字)
class David {
// protected method
protected int getBalance() {
return 1000000;
}
// package protected or "default" method
boolean knowsOop(){
return true;
}
}
There the method getBalance
can only be accesed by David
instances and David
subclasses ( create another thread for what is a subclass )
该方法getBalance
只能由David
实例和David
子类访问(为子类创建另一个线程)
The method knowsOop
can be accesses by anyone inside the package as David is defined.
该方法knowsOop
可以被包内的任何人访问,因为大卫是定义的。
Don't worry about this two access modifiers, they will make sense when you learn more about OOP and Java.
不要担心这两个访问修饰符,当您更多地了解 OOP 和 Java 时,它们会变得有意义。
Finally you should really, really take time to read:
最后,你真的应该花时间阅读:
http://java.sun.com/docs/books/tutorial/java/javaOO/index.html
http://java.sun.com/docs/books/tutorial/java/javaOO/index.html
I hope this helps
我希望这有帮助
回答by Andrey
the main reason is called encapsulation: don't give access to internal state of object.
主要原因称为封装:不要访问对象的内部状态。
回答by brabster
HThe public, protected and private modifiers control what other code can see those methods (or fields). It's about controlling the interface you're exposing.
H public、protected 和 private 修饰符控制哪些其他代码可以看到这些方法(或字段)。这是关于控制你暴露的接口。
The commonly useful ones are:
常用的有:
The public modifier: any other can see your method.
public 修饰符:任何其他人都可以看到您的方法。
The private modifier: no code other than your class and any inner classes can see your method.
private 修饰符:除了您的类和任何内部类之外,没有其他代码可以看到您的方法。
These would be useful for example if you wanted to ensure there was only a single instance of a class ever created (singleton pattern). You could make the constructor private, create a single instance and store is as a private member called instance, and provide a public method something like this:
例如,如果您想确保只创建了一个类的单个实例(单例模式),这些将很有用。您可以将构造函数设为私有,创建单个实例并将其存储为称为实例的私有成员,并提供如下所示的公共方法:
public static MyObject getInstance() {
return instance;
}
and so you can guarantee that there will only every be one instance.
所以你可以保证每个实例只有一个。
Update - another example as requested.
更新 - 根据要求的另一个例子。
Another example might be where you have a complicated public method and you want to break it down into simpler parts. You could break it down into simplr methods, each doing part of the job, but you wouldn't want other code to call those part methods, as they wouldn't work on their own - so you would make the smaller methods private, ensuring that they can't be called outside your class.
另一个例子可能是你有一个复杂的公共方法,你想把它分解成更简单的部分。您可以将其分解为 simplr 方法,每个方法都完成部分工作,但您不希望其他代码调用这些部分方法,因为它们无法单独工作 - 因此您会将较小的方法设为私有,确保他们不能在你的课外被调用。
回答by Dmitry
Privatemethods can be called only inside the class. You can call publicmethods of your class anywhere in program. Methods without access modifier are meant to have package visibility scope (it's called default), so you can invoke it anywhere in package, where class is defined.
私有方法只能在类内部调用。您可以在程序中的任何位置调用类的公共方法。没有访问修饰符的方法意味着具有包可见性范围(称为default),因此您可以在包中定义类的任何位置调用它。
See http://en.wikipedia.org/wiki/Object_oriented_programming#Encapsulation
见http://en.wikipedia.org/wiki/Object_oriented_programming#Encapsulation
回答by Mnementh
A public method can be accessed from everywhere, a private method only from the same class. The main advantage is the control over the API of an class. If I make only public what is needed, I can change the internal behaviour of a class , without breaking code depending on this class. You should care, because software changes often in the real world (at least it's my experience and others have it too) and the more every change breaks, the more energy you have to put into maintenance or the more bugs your software has. In the end it's a question of costs.
公共方法可以从任何地方访问,私有方法只能从同一个类访问。主要优点是可以控制类的 API。如果我只公开需要的东西,我可以改变一个类的内部行为,而不会破坏依赖于这个类的代码。你应该关心,因为软件在现实世界中经常发生变化(至少这是我的经验,其他人也有),而且每次更改中断的次数越多,你需要投入越多的精力进行维护,或者你的软件有更多的错误。归根结底是成本问题。
The possibility to hide internals of your class from users of this class to avoid breaking code by later changes is often called encapsulation or information hiding.
向此类的用户隐藏类的内部结构以避免以后更改破坏代码的可能性通常称为封装或信息隐藏。
The two options besides public and private are package (without an modifier) and protected. The package-accessible method can also be accessed from within classes of the same package. I cannot remember to used that option in any useful way. protected methods can be accessed from classes, that inherit the class in question. That is often used to create classes with concrete behaviour for a defined API of the base-class. For example could you implement a new List-class by extending AbstractListand you only need to implement get and size (and one set-method for modifiable lists). The other methods exposed by the API of List are defined in the base-class, calling the three other methods if needed.
除了 public 和 private 之外的两个选项是 package (没有修饰符) 和 protected。包可访问的方法也可以从同一包的类中访问。我不记得以任何有用的方式使用过该选项。可以从继承相关类的类访问受保护的方法。这通常用于为基类的已定义 API 创建具有具体行为的类。例如,您是否可以通过扩展AbstractList 来实现一个新的 List 类,而您只需要实现 get 和 size (以及一种用于可修改列表的 set-method )。List 的 API 公开的其他方法在基类中定义,如果需要,可以调用其他三个方法。
回答by BalusC
For starters, I would to start restrict the access as much as possible. Start with private
. If you happen to need the constructor, method or field from somewhere else, but cannot access it due to the restriction, then the next steps would be to ask yourself:
首先,我会尽可能地限制访问。开始private
。如果您碰巧需要其他地方的构造函数、方法或字段,但由于限制而无法访问它,那么接下来的步骤就是问自己:
- If it is a method, do you really need to access it? Does it change the behaviour of the class/instance? Shouldn't you let that class do the work? Shouldn't the current class (which needs that field or method) be brought tighter to that class?
- If it is a field, do you need to get or set its value? Shouldn't you add a method which does exactly that?
- 如果它是一个方法,你真的需要访问它吗?它会改变类/实例的行为吗?你不应该让那个班级来做这项工作吗?不应该将当前类(需要该字段或方法)更紧密地引入该类吗?
- 如果是字段,是否需要获取或设置其值?你不应该添加一个方法来做到这一点吗?
Point 1 avoids wrong coupling and point 2 improves encapsulation. Once you've considered the above and concluded that less restriction is really needed, then set it one step or more further open.
第 1 点避免错误耦合,第 2 点改进封装。一旦您考虑了上述内容并得出结论认为确实需要较少的限制,然后将其设置为一步或进一步开放。