1. Overview
1.概述
In the Java programming language, fields, constructors, methods, and classes can be marked with access modifiers. In this tutorial, we’ll talk about the private access modifier in Java.
在Java编程语言中,字段、构造函数、方法和类都可以用访问修饰符标记。在本教程中,我们将讨论Java中的private访问修饰符。
2. The Keyword
2.关键字
The private access modifier is important because it allows encapsulation and information hiding, which are core principles of object-oriented programming. Encapsulation is responsible for bundling methods and data, while information hiding is a consequence of encapsulation — it hides an object’s internal representation.
private访问修饰符很重要,因为它允许封装和信息隐藏,这是面向对象编程的核心原则。封装负责捆绑方法和数据,而信息隐藏是封装的结果–它隐藏了一个对象的内部表示。
The first thing to remember is that elements declared as private can be accessed only by the class in which they’re declared.
首先要记住的是,声明为private的元素只能被声明它们的类所访问。
3. Fields
3.场地
Now, we’ll see some simple code examples to better understand the subject.
现在,我们将看到一些简单的代码例子,以更好地理解这个主题。
First, let’s create an Employee class containing a couple of private instance variables:
首先,让我们创建一个Employee类,包含几个private实例变量。
public class Employee {
private String privateId;
private boolean manager;
//...
}
In this example, we marked the privateId variable as private because we want to add some logic to the id generation. And, as we can see, we did the same thing with manager attribute because we don’t want to allow direct modification of this field.
在这个例子中,我们把privateId变量标记为private,因为我们想在id生成中加入一些逻辑。而且,我们可以看到,我们对manager属性做了同样的事情,因为我们不想让这个字段被直接修改。
4. Constructors
4.构建者
Let’s now create a private constructor:
现在我们来创建一个private构造函数。
private Employee(String id, String name, boolean managerAttribute) {
this.name = name;
this.privateId = id + "_ID-MANAGER";
}
By marking our constructor as private, we can use it only from inside our class.
通过将我们的构造函数标记为private,我们可以只在我们的类中使用它。
Let’s add a static method that will be our only way to use this private constructor from outside the Employee class:
让我们添加一个静态方法,这将是我们从Employee类之外使用这个私有构造函数的唯一方式:。
public static Employee buildManager(String id, String name) {
return new Employee(id, name, true);
}
Now we can get a manager instance of our Employee class by simply writing:
现在,我们可以通过简单的编写来获得我们的Employee类的一个经理实例。
Employee manager = Employee.buildManager("123MAN","Bob");
And behind the scenes, of course, the buildManager method calls our private constructor.
当然,在幕后,buildManager方法调用我们的private构造函数。
5. Methods
5.方法
Let’s now add a private method to our class:
现在让我们给我们的类添加一个private方法。
private void setManager(boolean manager) {
this.manager = manager;
}
And let’s suppose, for some reason, we have an arbitrary rule in our company in which only an employee named “Carl” can be promoted to manager, although other classes aren’t aware of this. We’ll create a public method with some logic to handle this rule that calls our private method:
让我们假设,出于某种原因,我们公司有一个任意的规则,即只有名为 “Carl “的员工才能被提升为经理,尽管其他类并不了解这一点。我们将创建一个带有一些逻辑的public方法来处理这个规则,这个方法会调用我们的private方法。
public void elevateToManager() {
if ("Carl".equals(this.name)) {
setManager(true);
}
}
6. private in Action
6.私人在行动中
Let’s see an example of how to use our Employee class from outside:
让我们看一个如何从外部使用我们的Employee类的例子。
public class ExampleClass {
public static void main(String[] args) {
Employee employee = new Employee("Bob","ABC123");
employee.setPrivateId("BCD234");
System.out.println(employee.getPrivateId());
}
}
After executing ExampleClass, we’ll see its output on the console:
执行ExampleClass后,我们会在控制台看到它的输出。
BCD234_ID
In this example, we used the public constructor and the public method changeId(customId) because we can’t access the private variable privateId directly.
在这个例子中,我们使用了public构造函数和public方法changeId(customId),因为我们不能直接访问private变量privateId。
Let’s see what happens if we try to access a private method, constructor, or variable from outside our Employee class:
让我们看看如果我们试图从我们的Employee类之外访问一个private方法、构造函数或变量会发生什么。
public class ExampleClass {
public static void main(String[] args) {
Employee employee = new Employee("Bob","ABC123",true);
employee.setManager(true);
employee.privateId = "ABC234";
}
}
We’ll get compilation errors for each of our illegal statements:
我们的每个非法语句都会出现编译错误。
The constructor Employee(String, String, boolean) is not visible
The method setManager(boolean) from the type Employee is not visible
The field Employee.privateId is not visible
7. Classes
7.班级
There is one special case where we can create a private class — as an inner class of some other class. Otherwise, if we were to declare an outer class as private, we’d be forbidding other classes from accessing it, making it useless:
有一种特殊情况,我们可以创建一个private类–作为其他类的内部类。否则,如果我们将一个外层类声明为private,我们就会禁止其他类访问它,从而使它失去作用。
public class PublicOuterClass {
public PrivateInnerClass getInnerClassInstance() {
PrivateInnerClass myPrivateClassInstance = this.new PrivateInnerClass();
myPrivateClassInstance.id = "ID1";
myPrivateClassInstance.name = "Bob";
return myPrivateClassInstance;
}
private class PrivateInnerClass {
public String name;
public String id;
}
}
In this example, we created a private inner class inside our PublicOuterClass by specifying the private access modifier.
在这个例子中,我们通过指定private访问修饰符,在我们的PublicOuterClass中创建了一个private内类。
Because we used the private keyword, if we, for some reason, try to instantiate our PrivateInnerClass from outside the PublicOuterClass, the code won’t compile and we’ll see the error:
因为我们使用了private关键字,如果我们出于某种原因,试图从PublicOuterClass之外实例化我们的PrivateInnerClass,代码将无法编译,我们会看到错误。
PrivateInnerClass cannot be resolved to a type
8. Conclusion
8.结语
In this quick tutorial, we’ve discussed the private access modifier in Java. It’s a good way to achieve encapsulation, which leads to information hiding. As a result, we can ensure that we expose only the data and behaviors we want to other classes.
在这个快速教程中,我们讨论了Java中的private访问修改器。这是一个实现封装的好方法,它导致了信息隐藏。因此,我们可以确保只将我们想要的数据和行为暴露给其他类。
As always, the code example is available over on GitHub.
像往常一样,代码示例可在GitHub上获得。