Java access control: Do you really know protected keyword?

Source: Internet
Author: User
Tags modifier modifiers

Summary:

Within a class, its members (including member variables and member methods) can be interviewed by other classes, depending on the modifier of that member, and whether a class can be visited by other classes depends on the class's modifiers. There are four classes of class member access rights modifiers in Java: Private, none (by default.) Access permissions), protected and public, with only the package access permission and public ability to decorate a class (except for inner classes). In particular, a lot of books about Java are relatively 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 just need to be aware that in a project, you cannot have the same two package names. In other words, our package name cannot be repeated with the other package names in the project. This includes not only the package name that defines the package name, but also the class library referenced by the project. Look at the following examples:

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

The package name of the program we give ourselves 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 execute the program there is a packet conflict warning and a "java.lang.SecurityException:Prohibited package Name:java.lang" exception is thrown. For example, as seen in the.

              

          

In addition We need to note that if we use the package statement in the program, it must be the first code in the file except staring, otherwise it cannot be compiled.

Two. Overview of Java access permissions

In the interior of a class. Whether its members (including member variables and member methods) can be interviewed by other classes depends on the modifier of that member. There are four classes of class member access rights modifiers in Java:private, none (by default, package access permissions), protected, and public.

Its permissions control, as seen in the following table:

             

It is important to note that for classes in Java (not their internal members), the access permission modifiers are only public and "none" (that is, packet access). Instead of private and protected (there is a special case, only the inner class can be private or protected, for more on the inner class see my blog, "Internal Java Class review").

Therefore, for non-intrinsic classes. We can only grant them access to the package or public. If you don't want anyone else to have access to the class, you can designate all of the constructors as private. This prevents any person from creating objects of that class.

At this point, the object of the class can only be created inside its static member. This situation is a bit like a singleton pattern, like the following example:

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

In the four modifiers mentioned above. Besides protected, they are very well understood and mastered. Here's a brief description:

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

    • Private: A class member that is modified by public can only be interviewed in the class that defines it, and other classes are not available. In particular, we generally recommend that you set the member variable to private, and provide getter/setter to the outside world to access the member variables, which fully embodies the four characteristics of Java object-oriented (encapsulation, polymorphism. inheritance, abstraction) in the encapsulation of ideas;

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

      Because the true connotation 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"). All of the protected are relatively simple to introduce. It's basically a sentence. is: a member modified by protected is visible to this package and its subclasses.

Such a statement is a bit too vague and often causes 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 member variables of protected are similar.

  In essence, whether the invocation of the protected method is legitimate (compiled 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. If the same, it is lawful, otherwise, illegal.

Of course. In any case, subclasses are able to access inherited, protected methods that belong to them.

We can look at the following examples to understand.

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

//Demo sample one PackageP1; Public  class Father1 {    protected void F() {}//protected method in parent class Father1} PackageP1; Public  class Son1 extends Father1 {} PackageP11; Public  class Son11 extends Father1{} 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. The 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 the protected method F () comes from the Father1 class, in the same package P1 as the Test1 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 demo example above, classes Father1, Son1, and Test1 under the same package P1, Class Son11 under Package P11.

But 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. So the F () method is visible to the Test1 class and compiled through. The Clone () method is not visible to the Test1 class because the Clone () method in the Son1 class and the Son11 class originates from the class object under the Java.lang package, which is not in the same package as the Test1 class. compilation does not pass.

//Demo Sample II 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 is not in the same package P1 as the Test2 class, the Test2 class acts as a subclass of the MyObject2 class and is able to access inherited, protected methods that belong to it.

}}

In the demo sample above, class MyObject2 and Class Test2 are under Package P2 and P22 respectively.

Therefore, when calling MyObject2 's protected Method Clone () in class Test2 by reference to MyObject2, the compiler does not pass because class MyObject2 and class Test2 are not in the same package.

But we know that even though the protected method of the class Test2 clone () is derived from the class MyObject2 at its root. However, the Test2 class is a subclass of the MyObject2 class. is the ability to access 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()来自于Object类,而如今正是在Object的子类Test3类中訪问该方法,所以编通过。注意:  }}

In the demo sample above. Class MYOBJECT3 and Class Test3 are under Package P3 and P33 respectively. However, because the protected method of the MyObject3 class, Clone (), originates from the class object. It is now in the subclass Test3 class of the object class to access the method. So the compilation passes. The principle is similar to a demo sample.

It is important to note that MYOBJECT3 directly inherits from Test3, and Test3 directly inherits from object, and is visited in Test3 from the object class protected Method Clone (). Unlike example one, although Son1 's protected Method clone () also comes from the object class, Class Test1 is also a subclass of class object, but these three are not direct inheritance relationships, so "son1.clone ();" In Example one, the compilation does not pass.

//Demo sample 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. The protected Method Clone () is from the MyObject4 class, and the Test4 class is not in the same package as the MyObject4 class }} 

The demo sample is very similar to the demo sample 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). Another scenario: Subclasses are in the same package as the base class

//Demo sample 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 demo sample is very similar to the demo sample four. The only difference is 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 demo example, because the protected method clone () in class MyObject originates from the Test6 class, it is now called the Protected Method clone () in Test6, so the compilation passes.

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

In this demo sample. Although the class MyObject7 is in the same package P7 as the Test7 class. But because the protected method of the class Test7 clone () originates from the Java.lang.Object class. And it's 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), the modified variables are called class variables or static variables. static variables are shared with the class, and each instance shares the static variable. Initialized when the class is loaded.

Final: A variable declared final must be given an initial value at the time of declaration (of course. Except for the blank final case). And the modified variable cannot change 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. When modifying a method. As an abstract method.

Class has to have only one abstract method, the class must be defined as abstract, but the abstract class is not necessarily an abstract method.

Five. Summary

In the interior of a class. Whether its members (including member variables and member methods) can be visited by other classes depends on the modifier of that member, and whether a class can be interviewed by other classes depends on the modifiers of that class.

There are four classes of class member access rights modifiers in Java: Private. None (by default, the package access permission). protected and public, which only have the package access permission and public ability to decorate a class (except for inner classes). In particular. This paper focuses on the connotation and usage of protected keywords, 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 them have been specifically mentioned in other blog post, so there are not many other specific 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.

references

Protected in Java (specifically explained), and some issues related to the Clone () method
Access Permissions for Java
Java Foundation specific explanation (i) Java class members access permission modifiers (and class access permissions)

Java access control: Do you really know 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.