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


One of the three characteristics of object-oriented: Encapsulation

Concept:
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
3
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 {
    //attribute 
             //Nickname?
        private     String name;
            //Health value
        private     int health;
            //Intimacy
        private    int love;
            //Varieties
        private    String strain="Smart Labrador";
    
        
        
        
        //Get value read-only method
    public String getName() {
            return name;
        }



//set Assignment writable method

        public void setName(String name) {
            this.name = name;
        }





        public int getHealth() {
            return health;
        }





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





        public int getLove() {
            return love;
        }





        public void setLove(int love) {
            this.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"+this.name+"\n The health value is:"+health+"\n Intimacy with the host"+love+"I am a"+this.strain);    
                
                
            }
}
Dog.java
public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
    
        
        
        Dog dog=new Dog();
        dog.setName("Labrador retriever ");
        System.out.println(dog.getName());
        dog.setHealth(90);
        System.out.println(dog.getHealth());
        
    }

}

Tags: Java Attribute

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