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