Detailed explanation of the function of protected modifier and static modifier in Java programming _java

Source: Internet
Author: User
Tags modifier shallow copy static class

Protected
to talk about the protected access rights issue. Look at example 1 below:
Test.java

Class MyObject {} public
 
class Test {public
  static void Main (string[] args) {
    MyObject obj = new MyObject (); C5/>obj.clone (); Compile error.
  }
}

The error mentioned earlier appears: The method clone from the type Object isn't visiuable.
We have made it clear that object.clone () is the protected method. This means that the method can be accessed by subclasses of the same package (Java.lang) and it (Java.lang.Object). This is the MyObject class (default inheritance Java.lang.Object).
Similarly, test is a subclass of Java.lang.Object. However, you cannot access the protected method of another subclass in one subclass, although the two subclasses inherit from the same parent class.
Look at example 2 again:
Test2.java

Class MyObject2 {
  protected Object clone () throws Clonenotsupportedexception {return
    super.clone ();
  }
}
 
public class Test2 {public
  static void Main (string[] args) throws clonenotsupportedexception {
    MyObject2 obj = New MyObject2 ();
    Obj.clone (); Compile OK.
  }
}

Here, we override (override) the Clone () method of the parent class in the MyObject2 class, call the Clone () method in another class Test2, and compile it.
The reason for compiling it is obvious that when you override the Clone () method in the MyObject2 class, the MyObject2 class and the Test2 class are under the same package, so this protected method is visible to the Test2 class.
Analysis here, we are recalling the shallow copy and deep copy in Java, the declaration in chapter 2.2, ② overrides the Clone () method of the base class in a derived class and declares public. Now understand the reason for this sentence (in order for other classes to invoke the Clone () method of this class, the attribute of the Clone () method is set to public after the overload.)
Let's look at example 3 again:
Test3.java

Package 1
class MyObject3 {
protected Object clone () throws Clonenotsupportedexception {return
    Super.clone ();
  }
}
 
Package 2 Public
class Test3 extends MyObject3 {public
  static void Main (String args[]) {
    MyObject3 obj = new MyObject3 ();
    Obj.clone (); Compile error.
    Test3 tobj = new Test3 ();
    Tobj.clone ();//Complie OK.}
}

Here I use the Test3 class to inherit MyObject3, note that these two classes are different packets, otherwise it is the case of Example 2. The Clone () method of the instance tobj of the Test3 class is called in the Test3 class, and is compiled through. The Clone () method that also invokes instance obj of the MyObject3 class, compiles the error!
Unexpected result, does the protected method not be accessible by inheriting classes?
It must be clear that the class Test3 does inherit the class MyObject3 (including its Clone method), so you can call your own clone method in the class Test3. But the protected method of the class MyObject3 is not visible to the Test3 of the different buns.
Here's a quote from Java in a nutshell:
Protected access requires a little more elaboration. Suppose Class A declares a protected field x and is extended by Class B, which are defined in a different package (this L AST point is important). Class B inherits the Protected field X, and its code can access this field in the current instance of Stances of B that's code can refer to. This is does not mean, however, the Code of Class B can start reading the protected fields of arbitrary instances of A! If An object is A instance of A but are not a instance of B, its fields are obviously not inherited by B, and the Code of Class B cannot read them.
By the way, many Java books in the country are generally described in this way when introducing access rights (in different forms, consistent in content):
Access control for the method:


Static
1. Keyword static (remember these first, then look down)
1 static methods and static variables belong to a class, not to the object of the class.
2 static methods and static variables are referenced directly by the class name.
3 non-static methods and reference Non-static member variables cannot be invoked in static methods. Conversely, you can.
4 static variables are similar to the global variables of other languages in some programs, and can be accessed outside of the class if they are not private.
2. When to use static
When we create an instance of a class (object), we usually use the new method so that the data space of the class is created and its method can be invoked.
However, sometimes we want a class that can be created N objects (obviously the data space of these n objects is not the same), but some of the data for these n objects is the same, no matter how many instances of the class, the data has a copy of the memory for those instances (see Example 1). This is the case for static variables.
Another scenario is that you want a method that is not associated with any object of the class that contains it. That is, you can call this method even if you do not create an object. An important use of the static method is that it can be invoked without creating any objects (see Example 2). This is the case for static methods.
There is also a special use in the inner class, where a normal class is not allowed to be declared static, and only an inner class can be used. At this point, the internal class declared as static can be used directly as a generic class, without an instance of an external class (see Example 3). This is the case for static classes.
Example 1

public class Tstatic {
  static int i;
 
  Public tstatic () {
    i = 4;
  }
 
  Public tstatic (int j) {
    i = j;
  }
 
  public static void Main (String args[]) {
    System.out.println (TSTATIC.I);
    Tstatic t = new tstatic (5); Declares an object reference and instantiates it. At this time i=5
    System.out.println (T.I);
    Tstatic tt = new tstatic (); Declares an object reference and instantiates it. At this time i=4
    System.out.println (T.I);
    System.out.println (TT.I);
    System.out.println (T.I);
  }


Results:

0
5
4
4
4

The static variable is created when the class is loaded, and the static variable exists as long as the class exists. They must be initialized when they are defined. I is not initialized in the example above, so the default initial value of 0 is obtained. The static variable can be initialized only once, and the static variable only accepts the last initialization.
This is actually the problem of multiple instances sharing a static variable.

Example 2
Not declared as static

Class ClassA {
  int b;
 
  public void Ex1 () {}
 
  class ClassB {
    void Ex2 () {
      int i;
      ClassA a = new ClassA ();
      i = a.b; This is where member variable B a.ex1 () is accessed through object references
      Access member functions Ex1
    }}


Declared as static

Class ClassA {
  static int b;
 
  static void Ex1 () {}
}
 
class ClassB {
  void Ex2 () {
    int i;
    i = classa.b; The member variable B classa.ex1 () is accessed through the class name, and
    /or the member function is accessed through the class name Ex1
  }
}

When using static methods, be aware that non-static methods cannot be invoked in static methods and reference Non-static member variables (this or super cannot be referenced in any way in the static method). The reason is simple, for static things, when the JVM loads the class, it opens up these static spaces in memory (so it can be referenced directly through the class name), and the class of non-static methods and member variables is not instantiated yet.
So if you want to use non-static methods and member variables, you can instantiate the class of the method or member variable directly in the static method. This is what public static void main does.

Example 3

public class Staticcls {public
  static void Main (string[] args) {
    outercls.innercls oi = new Outercls.innercls (); /This does not need to be new one Outercls
  }
}
 
class Outercls {public
  static class Innercls {
    innercls () {
      System.out.println ("Innercls");}}


Results:

Innercls

3. Static initialization
a variable defined by a static takes precedence over any other non-static variable, regardless of the order in which it appears. A static code block (followed by a piece of code after "static{") is used to initialize an explicit static variable, which is initialized only once, and when the class is first loaded. Look at the example below.

 class Value {static int c = 0;
  Value () {c = 15;
  } Value (int i) {c = i;
  static void Inc () {C + +;
  Class Count {public static void prt (String s) {System.out.println (s);
 
  } Value v = new value (10);
  Static Value v1, V2;
    static {PRT ("in the Static" of CALSS Count v1.c= "+ v1.c +" v2.c= "+ v2.c);
    V1 = new Value (27);
    PRT ("In the Static" of CALSS Count v1.c= "+ v1.c +" v2.c= "+ v2.c);
    v2 = new Value ();
  PRT ("In the Static" of CALSS Count v1.c= "+ v1.c +" v2.c= "+ v2.c);
    } public class Tstaticblock {public static void main (string[] args) {count ct = new Count ();
    Count.prt ("In the main:");
    Count.prt ("ct.c=" + ct.v.c);
    Count.prt ("v1.c=" + count.v1.c + "v2.c=" + count.v2.c);
    Count.v1.inc ();
    Count.prt ("v1.c=" + count.v1.c + "v2.c=" + count.v2.c);
  Count.prt ("ct.c=" + ct.v.c); }
}


Results:

In the static blocks of CALSS count V1.c=0 v2.c=0 in the static blocks of
CALSS Count v1.c=27 v2.c=27 in the
static Block of Calss Count v1.c=15 v2.c=15 in the
main:
ct.c=10
v1.c=10
v2.c=10 v1.c=11 v2.c=11 ct.c=11

Either V,V1 or V2, the member variables they manipulate are the same static variable C.
Initialize V1,v2 (static Value v1, V2;) in class count, then initialize the static code block (static{}), and finally initialize v.

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.