Access modifier in java

Source: Internet
Author: User

Access modifier in java

Compared with the public, proctected, and private access control in c ++, java has a default access control.
The four access control permissions in java are described as follows:
1) private is only visible to this class (same as c ++)
2) by default, this package is visible/accessed in the package (c ++ does not)
3) protected is visible to this package and all sub-classes (c ++ does not have the concept of this package, and the default access can be accessed by sub-classes under other packages)
4) public is visible to all classes (same as c ++)

1) 4) Same as c ++, 2) 3) perform a simple test.

3) protected:

package com.behavior;public class Parent {    protected int i = 3;}
Package com. behavior; // There is no inheritance relationship with the Parent in the same package. public class Children {public void action () {Parent parent = new Parent (); System. out. print (parent. I );}}
package com.stratege;import com.behavior.Children;public class ChildrenTest {        public static void main(String [] args) {            Children children = new Children();            children.action();        }}

Verify that protected has the permission to access the package.

2) access to the package is tested by default.
Modify the access permission of variable I in the Parent as follows. The Children and ChildrenTest remain unchanged.

package com.behavior;public class Parent {    int i = 3;}

Verification: the default access permission to the package

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.