Packaging
Concept: Refers to the hidden object's properties and implementation details, only provide public access to the external way. is one of the three main characteristics of object-oriented.
Benefit: Isolate the change. Improve reusability. Improve security.
Encapsulation principle:
? Hide content that you don't need to provide externally.
? Hides properties, providing public methods for accessing them.
In Java, you can implement information hiding for members of a class by setting certain access permissions on the members of the class.
As the following student class, the encapsulation is used to privatize the properties in the class name, age, and score so that the external cannot access them directly, only through the public type of their methods.
classStudent {PrivateString name;//declares a property and sets it as a private type, acting as a wrapper Private intsex; PublicString GetName () {//set the Getter method, because the variable is set to private, the object cannot access the property in the class, and the getter method is required to get the variable returnname; } Public voidSetName (String name) {//The setter method is set, because the variable is set to private, the object cannot access the property in the class, and a setter method is required to assign a value to the variable This. Name =name; } Public intGetsex () {returnsex; } Public voidSetage (intAge ) { This. Age =Age ; } }
reasons for doing this in Java:
- Separating data from behavior is the object-oriented concept of java.
object is the attribute + behavior, encapsulation is the object's private properties are encapsulated, only through their own public behavior to change (get) The private property information inside the object, and those who use the method is the interface for other objects, only through the interface to change (get) The private properties of the object.
Imagine that the sex field of the student class above represents gender, in theory, sex only accepts two values, ' 0 ' and ' 1 ', but if you set the sex field to public, it's hard to limit your users to assigning only ' 0 ' or ' 1 ' values to it. By setting sex to private and then using Setsex () to set the gender, you can control this behavior completely. And you can control only get cannot set, or vice versa, but if it is public it will not. There's a little bit of a property. We may not want other users to write about our properties, which can be done directly without writing the Setx method. This is the read-only attribute.
Why is the Java bean variable type private, but it provides a get (), set () method?