Java object-oriented features: encapsulation and java
One of the three features of object-oriented architecture: Encapsulation
Concept:
Hiding some information of a class inside the class does not allow direct access by external programs. Instead, you can use the method class provided by the class to perform operations and access to the hidden information.
Advantages of encapsulation:
Hide the implementation details of a class
Easy to add control statements
Convenient modification implementation
Data can only be accessed through specified methods
Encapsulation steps:
1. Modify the visibility of attributes >>>>>> set to private
2. Create a public getter/setter method >>>>>> for reading and writing Properties
3
Add an attribute control statement to the getter/setter method >>>>>> to determine the validity of the attribute value
Encapsulated Shortcut Keys: Shift + Alt + S + R
Not much nonsense, on the chestnut:
Public class Dog {// attribute // nickname private String name; // health value private int health; // intimacy private int love; // species private String strain = "smart ladeldorado dog"; // read-only public String getName () {return name ;} // set value writeable 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 ("The 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 information of a specific dog object */public void print () {System. out. println ("Pet White: My name is" + this. name + "\ n health value:" + health + "\ n intimacy with the master" + 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 ("labeldorado"); System. out. println (dog. getName (); dog. setHealth (90); System. out. println (dog. getHealth ());}}