Java basics-an example of access permissions, a java permission example
1. Review access Modifiers
= Public: the class, attribute, and method modified by it. It can be accessed not only across classes, but also across packages.
= Private: you can modify data members, constructor methods, methods, and classes. The modified members can only be accessed by the class and cannot be accessed by the quilt class.
= Protected: it can be used to modify data members, constructor methods, methods, and classes. It can be accessed by this class, the same package, or its subclass members. (if it is a subclass, it can be cross-package)
= Default: only access from the same package is allowed without any Modifier
Ii. code example
1 package dog; 2 3 public class Dog {4 // public 5 public void publicMethod () {6 System. out. println ("publicMethod"); 7} 8 9 // protected 10 protected void protectedMethod () {// The method declared as protected. The quilt class can inherit 11 systems. out. println ("protectedMethod"); 12} 13 14 // default 15 void defaultMethod () {16 System. out. println ("defaultMethod"); 17} 18 19 // private 20 private void privateMethod () {// This method can only be called within the class 21 System. out. println ("privateMethod"); 22} 23}
1 class T {2 public static void main (String [] args) {3 Dog d = new Dog (); // you can access 4 d. publicMethod (); // you can access 5 d. protectedMethod (); // you can access 6 d. defaultMethod (); // you can access 7 // d. privateMethod (); // Private method, which cannot be accessed outside the class 8} 9}
1 // based on the above example, demonstrate cross-package situation 2 package cat; // The package and dog package are not together 3 4 import dog. dog; 5 6 public class Cat {7 void test () {8 Dog dog = new Dog (); 9 10 dog. publicMethod (); // 11 // dog. protectedMethod (); it cannot be 12 // dog. privateMethod (); it cannot be 13 // dog. defaultMethod (); not allowed 14} 15}
1 // demonstrate the access in the subclass Based on the Scheme. 2 class NiceDog extends Dog {3 void test () {4 Dog dog = new Dog (); 5 dog. publicMethod (); // 6 protectedMethod (); // The member modified by protected can be inherited and called 7 // dog. protectedMethod (); not 8 // dog. privateMethod (); it cannot be 9 // dog. defaultMethod (); not 10 11} 12}