First, the basic concept
(a) The three main characteristics of object-oriented: 1. Encapsulation 2. Inheritance 3. Polymorphism
(ii) Encapsulation: Hide the implementation details and provide public access (interfaces) externally.
One embodiment of encapsulation: to privatize the properties and provide a corresponding setxxx GetXXX method to access them.
Benefits of Encapsulation:
1. Improve security. Direct access to details is not allowed. and accessible through public means, to achieve control.
2. Improved ease of use.
3. Improved reusability.
4. Changes in isolation. Later applied to layered design.
Second, the example code
Requires a privatization package to print the age of the person.
1 class Person2 {3 Private intAge ;4 //for private data, it can be accessed by means of a method. 5 Public voidSetage (inta)6 {7 //the data can be controlled. 8 if(a<0 | | a>130){9 Throw NewRuntimeException (A + "incorrect value");//Throw ExceptionTen}Else{ OneAge =A; A } - } - the Public intGetage () { - returnAge ; - } - voidspeak () { +System.out.println ("age=" +Age ); - } + A } at - classPersondemo - { - Public Static voidMain (string[] args) { - //creates an object of person, invoking the property and behavior of the person. -Person p =NewPerson (); inP.setage (20); - p.speak (); to } +}
Third, the code to run
If you compile the Java code with an issue that encodes the GBK characters, you should use the-encoding parameter to indicate how the encoding is encoded: javac-encoding UTF-8 Xx.java
1. Input command: javac-encoding UTF-8 Persondemo.java (code in compiled Persondemo file)
2. Input command: Java Persondemo (execute code in Persondemo file)
Introduction to Java Object-oriented encapsulation example (i)