Java access control: Do you really know the protected keyword?

Source: Internet
Author: User
Tags modifier modifiers

Summary:

Within a class, its members (including member variables and member methods) can be accessed by other classes, depending on the modifier of that member, and whether a class can be accessed by another class, depending on the class's modifiers. There are four classes of class member access rights modifiers in Java: Private, none (by default, package access), protected and public, where only package access and public can decorate a class (except for inner classes). In particular, many of the books that introduce Java are more general in protected and often cause misunderstanding. Therefore, this paper focuses on the connotation and usage of protected keywords, and introduces some other modifiers.

Copyright Notice:

This article original nerd Rico
Author Blog address: http://blog.csdn.net/justloveyou_/

I. Package

With regard to the use of packages, we only need to pay attention to: In a project, can not have the same two package name, that is, our package name can not be duplicated with the other package name in the project, this includes not only the custom package name also includes the package name of the class library referenced by the project. Look at the following example:

package java.lang;publicclass MyObject {    publicstaticvoidmainthrows CloneNotSupportedException {        new Object();        System.out.println(o.hashCode());    }}

The package name of our program is Java.lang, in fact, we know that Java.lang is the package name used by the JDK. The program compiles normally, but when we run the program there is a packet conflict warning and a "java.lang.SecurityException:Prohibited package Name:java.lang" Exception is thrown, as shown in.

              

          

In addition, we need to note: If we use the package statement in the program, then it must be the file in addition to the first sentence of the program code, otherwise it cannot be compiled.

Two. Overview of Java access rights

Within a class, its members (including member variables and member methods) can be accessed by other classes, depending on the modifier of that member. There are four classes of class member access rights modifiers in Java:private, none (by default, package access), protected, and public. Its permissions control is shown in the following table:

             

It is important to note that for classes in Java (not their internal members), their access modifiers only have public and "none" (that is, package access), without private and protected (with a special case, Only internal classes can be private or protected, for more information on internal classes see my blog, "Internal Java Class review". therefore, for non-intrinsic classes, we can only give them package access or public. If you don't want anyone else to have access to the class, you can designate all the constructors as private, preventing anyone from creating objects of that class. At this point, the object of the class can only be created inside its static members, which is a bit like a singleton pattern, as in the following example:

 class Test {       // private Constructor!       privateTest() {}       // Allow creation via static method:       publicstaticgetTest() {           returnnew Test();       }    }

In the above mentioned four kinds of modifiers, except protected, are well understood and mastered, we are here to briefly:

    • Public : class members that are modified by public can be accessed directly by all classes;

    • Private: A class member that is modified by public can only be accessed in the class in which it is defined, and other classes are not accessible. In particular, we generally recommend to set the member variable to private, and provide getter/setter to the outside world to access the member variables, this practice fully embodies the four main features of Java object-oriented (encapsulation, polymorphism, inheritance, abstraction) in the packaging idea;

    • Package access permissions: Package access is the default permission in Java, and class members with package access can only be accessed by classes in the same package.

      Because the true meaning of the protected keyword is not easy to understand, we'll cover the protected keyword in the next section.

Three. The true meaning of protected keywords

A lot of books about the Java language (including "Java Programming ideas") are simple to compare the protected introduction, which is basically a sentence, that is, the members who are protected decorated are visible to this package and its subclasses. This is a bit too vague, and it often leads to misunderstanding. For protected members, whether the numerator class and the superclass are treated in the same package, the invocation of the protected method is described as an example, and the protected member variable is similar.

  In essence, whether the invocation of the protected method is legal (compile or not) is the key to see whether the called protected method is the same as the package corresponding to the class in which the calling code is located, and if it is the same, it is legal; Of course, in any case, the subclass is able to access the inherited protected methods that belong to it.

We can look at the following examples to understand.

1). First case: The subclass is not in the same package as the base class

//Example One PackageP1; Public  class Father1 {    protected void F() {}//protected method in parent class Father1} PackageP1; Public  class Son1 extends Father {} PackageP11; Public  class Son11 extends Father{} PackageP1; Public  class Test1 {     Public Static void Main(string[] args) {Son1 Son1 =NewSon1 (); SON1.F ();//Compile ok,protected method F () from the Father1 class, in the same package P1 as the Test1 classSon1.clone ();//Compile error,protected Method Clone () is from the object class and is not in the same package as the Test1 classSon11 son =NewSon11 (); SON11.F ();//Compile OK, although the Son11 class is in package P11, but protected method F () is from the Father1 class, in the same package Test1 as the P1 classSon11.clone ();//Compile error,protected Method Clone () is from the object class and is not in the same package as the Test1 class}}

In the example above, classes Father1, Son1, and Test1 under the same package P1, Class Son11 under Package P11. However, we know that, regardless of the Son1 class or the Son11 class, their protected method F () originates from the class Father1 in the P1 package, and because Test1 is also in the P1 package, the F () method is visible to the Test1 class and compiled through. However, because the Clone () method in the Son1 class and the Son11 class originates from the class object under the Java.lang package, and the Test1 class is not in the same package, the Clone () method is not visible to the Test1 class and the compilation does not pass.

//Example two PackageP2;class MyObject2 {protectedObjectClone()throwsclonenotsupportedexception {return Super. Clone (); }} PackageP22; Public  class Test2 extends MyObject2 {     Public Static void Main(String args[]) {MyObject2 obj =NewMyObject2 (); Obj.clone ();//Compile error,protected Method Clone () from the MyObject2 class, not in the same package P1 as the Test2 classTest2 tobj =NewTest2 (); Tobj.clone ();//Complie OK, although the protected Method clone () is from the MyObject2 class, and the Test2 class is not in the same package P1, but the Test2 class is a subclass of the MyObject2 class, is to have access to inherited, protected methods that belong to it. }}

In the example above, class MyObject2 and Class Test2 are under Package P2 and P22 respectively. Therefore, when invoking MyObject2 's protected Method Clone () in class Test2 by reference to MyObject2, the compilation does not pass because class MyObject2 and class Test2 are not in the same package. But we know that although the protected Method clone () of class Test2 originates from the class MyObject2, the Test2 class, as a subclass of the MyObject2 class, is able to access the inherited protected methods that belong to it.

//示例三package p3;class MyObject3 extends Test3 {}package p33;publicclass Test3 {  publicstaticvoidmain(String args[]) {    new MyObject3();    // Compile OK,protected方法clone()来自于Test3类,而现在正是在Test3类中访问该方法  }}

In the example above, class MyObject3 and Class Test3 are under Package P3 and P33 respectively. However, because the protected method of the MyObject3 class, Clone (), is derived from the class Test3 at the root, and is now accessed in the Test3 class, it is compiled, and the principle is similar to the example.

//example four  package  P4;class MyObject4 extends Test4 {protected  Object clone  () throws  clonenotsupportedexception {return  Span class= "Hljs-keyword" >super . Clone (); }}package  p44; public  class  test4  { Span class= "Hljs-keyword" >public static  void  main  (String args[]) {MyObject4 obj = new  My Object4 (); Obj.clone (); //Compile error,protected Method Clone () from the MyObject4 class, and the Test4 class is not in the same package as the MyObject4 class }} 

The example is similar to example three, except that the class MyObject4 overrides the protected method clone () inherited from class Test4. Thus, MyObject4 's protected Method clone () originates from the class itself rather than the Test4 class. The class MyObject4 and class Test4 are not in the same package, so the compilation does not pass.

2). Second scenario: Subclasses are in the same package as the base class

///Example five PackageP5;class MyObject5 {protectedObjectClone()throwsclonenotsupportedexception {return Super. Clone (); }} Public  class Test5 {     Public Static void Main(string[] args)throwsclonenotsupportedexception {MyObject5 obj =NewMyObject5 (); Obj.clone ();//Compile ok,protected Method Clone () is from the MyObject5 class, and the Test5 class is in the same package as the MyObject5 class}}

The example is similar to example four, except that the class MyObject5 is in the same package P5 as the class Test5. Because they are in the same package, they are compiled through.

//示例六package p6;class MyObject6 extends Test6{}publicclass Test6 {  publicstaticvoidmain(String[] args) {    new MyObject6();    obj.clone();        // Compile OK  }}

In this example, because protected method Clone () in class MyObject originates from the Test6 class, it is now the protected method clone () that is called in Test6, so the compilation passes.

//示例七package p7;class MyObject7 extends Test7 {    publicstaticvoidmain(String[] args) {        new Test7();        // Compile Error.  }}publicclass Test {}

In this example, although the class MyObject7 is in the same package P7 as the Test7 class, the protected Method clone () of the class Test7 originates from the Java.lang.Object class, and it is not in the same package as MYOBJECT7, so the compilation does not pass.

Four. Other modifiers

Static: modifier variables and inner classes (which cannot be decorated with regular classes), where the modified variable is called a class variable or a static variable. static variables exist with the class, and each instance shares this static variable, which is initialized when the class loads.

Final: A variable declared final must be given an initial value at the time of declaration (except, of course, a blank final case), and the modified variable cannot modify the value. When a class is decorated, the class cannot derive a subclass, and the method cannot be overridden by the quilt class when the method is decorated. If the reader wants to have a deeper understanding of final, please go to my blog, "Java inheritance, polymorphism and class reuse."

Abstract: Modifies classes and methods. When a class is decorated, the class cannot create an object, or an abstract method when the method is decorated. Class has to be defined as abstract, as long as there is an abstract method, but the abstract class is not necessarily an abstract method.

Five. Summary

Within a class, its members (including member variables and member methods) can be accessed by other classes, depending on the modifier of that member, and whether a class can be accessed by another class, depending on the class's modifiers. There are four classes of class member access rights modifiers in Java: Private, none (by default, package access), protected and public, where only package access and public can decorate a class (except for inner classes). In particular, this article highlights the connotation and usage of the protected keyword, and introduces some other modifiers.

Six. Description

In the overview of Java access control: Do you really understand the protected keyword? "In the process, we involve a lot of knowledge points, some of which we have specifically mentioned in other blog post, so there is no more detailed elaboration, here are the corresponding links:

If the reader wants to learn more about the Java Internals, please visit my blog, "Java Internal Class review";
If the reader wants to learn more about the final keyword, please go to my blog, "Java inheritance, polymorphism and class reuse."
If the reader wants to learn more about Java cloning, please take a look at my blog, Java String Overview (next article), this article uses a subsection to elaborate on the principle and usage of cloning in Java, and reveals the particularity of the String object in the cloning process.

Reference

Protected in Java (detailed), and some questions about the Clone () method
Access Permissions for Java
Java Basics (I) class member access modifiers for Java (and class access rights)

Java access control: Do you really know the protected keyword?

Related Article

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.