Differences between private, protected, public, and default in Java-001

Source: Internet
Author: User

Public

With maximum access, you can access any class, interface, exception, etc. under Classpath. It is often used for external situations, i.e. the form of an interface to an object or class outside.

Protected

The main function is to protect the subclass. It means that a subclass can be decorated with its members, others cannot, it is equivalent to an inherited thing passed to a subclass.

Default

Sometimes also known as friendly, it is designed for this package access, any class, interface, exception, etc. under this package can be accessed by each other, even if the parent class is not decorated with protected members.

Private

Access is limited to the inside of the class, and is a encapsulation embodiment, for example, most member variables are modifier private, and they do not want to be accessed by any other external class.

Note: Java access control is stuck at the compiler level, that is, it does not leave any traces in the. class file, only access control checks during compilation. In fact, by means of reflection, it is possible to access any member of any class under any package, for example, to access a private member of a class.

Difference:

Public: can be accessed by all other classes

Private: can only be accessed and modified by themselves

Protected: The class in itself, subclasses, and the same package can access

Default: Classes in the same package can be accessed and declared without modifiers, which are considered friendly.

Differences between private, protected, public, and default in Java-001

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.