The difference between the permissions modifier public, private, protected, and default in Java

Source: Internet
Author: User
Tags modifier
1. Public

Classes, member variables, and member functions can be decorated without any restrictions, in the same package, or classes in different packages are free to access


2. Private

member variables and member functions can be decorated and can only be used in this class


3. Default

(Do not write permission modifiers, or default permissions) can be decorated with classes, member variables, and member functions, which are freely accessible in the same package. If the child class and the parent class are not in the same package, the subclass can inherit the member variables and member functions of the default permission in the parent class, but cannot be used because of insufficient permissions


4, Protected

Protected permissions first have the same functionality as default, but this permission only modifies member variables and member functions

5. Inheritance and access rights

(1), if inheritance occurs within the same package:
Subclasses can inherit all the variables of the parent class, but the subclass object can only use the public, protected, default member variables in the parent class, and cannot use the private variable;
(2), if it is a cross-package inheritance:
For the public variable in the parent class, the subclass can be inherited and can be used;
For the protected variable in the parent class, the subclass can be inherited and can be used, but not subclasses are not available;
For the default variable in the parent class, the subclass can inherit and not be used;
For private variables in the parent class, subclasses can inherit and are not available.

The difference between the permissions modifier public, private, protected, and default in Java

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.