Class member declaration Summary: public, friendly, Private, protected

Source: Internet
Author: User

After learning Java for two years, I suddenly found myself confused about the basic concepts of public, friendly, private, and protected, so I opened thinking in Java se...

Summary:

Public:The data member and member Methods declared as public can be used by all clients.ProgramStaff use.

Friendly:For all classes in the same package, if the two classes are placed in the same directory but the package is not declared, Java considers the two classes to belong to the same package, that is, the friendly data member and member methods are available.

PRIVATE:It cannot be seen by the outside world and can only be called by the member methods in the class. To implement the Java "Hide Implementation Details" principle, data members should be declared as private. If the constructor is declared as private, the client programmer cannot directly generate the object of this class, and can only generate the object of this class through the static method provided by the class. Is this the "factory model" in "Design Model?

Example:

Public Class {
Private (){}
Public static makea (){
Return new ();
}

Public static void main (string [] ARGs ){
//!~ A A = new A (); error, can't use new to create an object
A A = A. makea ();
}
}

Protected:A member declared as friendly can only be called by the class in the same package. If you want a class to inherit the class in another package, you can call the data member and member methods of the class, you need to declare the data member and member method as protected. For classes in the same package, protected serves as friendly.

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.