Introduction to Java Object-oriented encapsulation example (i)

Source: Internet
Author: User
Tags throw exception

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.