Access modifiers in Java

Source: Internet
Author: User

Compared to C + + in public,proctected, private three access control, Java more than the default access control.
Four types of access control permissions in Java are described briefly as four sentences:
1) Private only this class is visible (same as C + +)
2) default to this package visible/in-package access (C + + not)
3) Protected is visible to this package and all subclasses (there is no concept of this package in C + +, more than the default access can be accessed by subclasses under other packages)
4) public visible to all classes (same as C + +)

1) 4) do a simple test with C + +, 2) 3)

3) protected the package is visible to the following tests:

package com.behavior;publicclass Parent {    protectedint3;}
package com.behavior; With parent under the same package, no inheritance relationship  public  class  Children {public  void  action         () {Parent parent = new  parent (); System.    out . Print (PARENT.I); }}
package com.stratege;import com.behavior.Children;publicclass ChildrenTest {        publicstaticvoidmain(String [] args) {            new Children();            children.action();        }}

Authentication: Protected permissions for in-package access

2) default for in-Package access testing
The variable i access permission in parent is modified as follows, children, childrentest unchanged

package com.behavior;publicclass Parent {    int3;}

Validation: Default permissions for in-package access

Access modifiers 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.