One of the three characteristics of Java object-oriented: Encapsulation

One of the three characteristics of object-oriented: Encapsulation

Some information of the class is hidden inside the class, which is not allowed to be directly accessed by external programs. Instead, the operation and access to the hidden information are realized through the method class provided by the class

Benefits of encapsulation:
Hide class implementation details
Easy to add control statement
Easy to modify and implement
Data can only be accessed by specified methods

Encapsulation steps:
1. Modify the visibility of attributes to private
2. Create a public getter/setter method > > for reading and writing attributes
Add the property control statement in the getter/setter method to judge the validity of the property value

Encapsulated shortcut: Shift+Alt+S+R

Don't talk too much, chestnuts:

public class Dog {
        private     String name;
            //Health value
        private     int health;
        private    int love;
        private    String strain="Smart Labrador";
        //Get value read-only method
    public String getName() {
            return name;

//set Assignment writable method

        public void setName(String name) {
   = name;

        public int getHealth() {
            return health;

        public void setHealth(int health) {
            if (health<0 || health>100) {
                System.out.println("Health value must be between 0 and 100");
   = health;

        public int getLove() {
            return love;

        public void setLove(int love) {
   = love;

        public String getStrain() {
            return strain;

        public void setStrain(String strain) {
            this.strain = strain;

     * Output specific dog object information
            public void print()
            System.out.println("Pet confession: my name is""\n The health value is:"+health+"\n Intimacy with the host"+love+"I am a"+this.strain);    
public class Test {

     * @param args
    public static void main(String[] args) {
        Dog dog=new Dog();
        dog.setName("Labrador retriever ");


Tags: Java Attribute

Posted on Tue, 07 Apr 2020 09:43:30 -0700 by AliasXNeo