First, review the access modifier
==public: Classes, properties, methods, which are modified by it, can be accessed not only across classes, but also across packages (package)
==private: Can modify the data members, construction methods, methods, can not decorate the class, the members that it modifies can only be accessed by this class, cannot access the quilt class
==protected: Can be modified data members, construction methods, methods, can not be decorated class, the class, the same package, or its subclass members access (if it is a subclass, can cross-package)
= = Default: Do not add any modifiers, only allow access in the same package
Second, the code example
1 PackageDog;2 3 Public classDog {4 //of public5 Public voidPublicmethod () {6System.out.println ("Publicmethod");7 }8 9 //Protection ofTen protected voidProtectedmethod () {//methods that are declared as protected can be inherited by the quilt class OneSystem.out.println ("Protectedmethod"); A } - - //the default the voidDefaultmethod () { -System.out.println ("Defaultmethod"); - } - + //of Private - Private voidPrivatemethod () {//This method can only be called inside a class +System.out.println ("Privatemethod"); A } at}
1 classT {2 Public Static voidMain (string[] args) {3Dog d =NewDog ();//can access4D.publicmethod ();//can access5D.protectedmethod ();//can access6D.defaultmethod ();//can access7 //D.privatemethod ();//private methods that cannot be accessed outside of the class8 }9}
1 //On the basis of the above example, the case of cross-package is demonstrated2 PackageCat//not with the dog bag .3 4 ImportDog. Dog;5 6 Public classCat {7 voidTest () {8Dog dog =NewDog ();9 TenDog.publicmethod ();//can be One //Dog.protectedmethod (); not allowed. A //Dog.privatemethod (); not allowed. - //Dog.defaultmethod (); not allowed. - } the}
1 //On the basis of the preceding example, demonstrate the access in the subclass2 classNicedogextendsDog {3 voidTest () {4Dog dog =NewDog ();5Dog.publicmethod ();//can be6Protectedmethod ();//a member that is protected decorated can be inherited, and thus called7 //Dog.protectedmethod (); not allowed.8 //Dog.privatemethod (); not allowed.9 //Dog.defaultmethod (); not allowed.Ten One } A}
Java Basics--an example of access rights