Java final keyword detailed _php tips

Source: Internet
Author: User
Tags anonymous constant stringbuffer

Speaking of final keyword, presumably many people are not unfamiliar with the use of anonymous internal classes may often use the final keyword. In addition, the string class in Java is a final class, so today we come to understand the use of the final keyword.
Main introduction: First, the final keyword basic usage. Two. Deep understanding of final keywords

I. Basic usage of the final keyword

In Java, the final keyword can be used to decorate classes, methods, and variables (including member variables and local variables). Here are three ways to understand the basic usage of the final keyword.

  1. Cosmetic class

When a class is decorated with final, it indicates that the class cannot be inherited. In other words, if a class you never let him be inherited, it can be decorated with final. The member variables in the final class can be final as needed, but note that all member methods in the final class are implicitly specified as final methods.

When using the final modifier class, be careful to choose, unless the class is really not intended to be inherited or for security reasons, try not to design the class as the final class.

2. Modification method

The following passage is excerpted from the fourth edition of Java Programming ideas, page 143th:

"There are two reasons to use the final method." The first reason is to lock the method in case any inheriting class modifies its meaning, and the second reason is efficiency. In an earlier version of the Java implementation, the final method was converted to an inline call. But if the method is too large, you may not see any performance boost from the inline call. In the most recent Java version, you do not need to use the final method for these optimizations. “

Therefore, the method is set to final only if you want to explicitly prohibit the method from being overwritten in a subclass.

Note: The private method of a class is implicitly specified as the final method.

  3. Modifying variables

The modified variable is the most used place in final, which is the focus of this article. First, take a look at the basic syntax of the final variable:

For a final variable, if it is a variable of the base data type, its value cannot be changed once it is initialized, and if it is a variable of a reference type, it cannot be directed to another object after it has been initialized.

For example:

  

In the preceding section of the code, the values for the variables I and obj are not correct.

Two. Deep understanding of final keywords

After understanding the basic usage of the final keyword, let's take a look at where the final keyword is easy to confuse.

1. What is the difference between the final variable of a class and a normal variable?

When you apply final to a member variable of a class, a member variable (note is a member variable of a class, where a local variable is only guaranteed to be initialized before use) must be initialized in the definition or constructor, and the final variable can no longer be assigned once the assignment has been initialized.

  So what's the difference between the final variable and the ordinary variable? Let's take a look at the following example:

public class Test {public
  static void Main (string[] args) {
    String a = "Hello2"; 
    Final String b = "Hello";
    String d = "Hello";
    String C = b + 2; 
    String E = d + 2;
    System.out.println ((A = = c));
    System.out.println ((A = = e));
  }

True
False

We can think about the output of this problem first. Why is the first comparison true and the second comparison to Fasle.

This is the difference between the final variable and the ordinary variable, and when the final variable is the base data type and the string type, the compiler will use it as a compile-time constant if it knows its exact value during compilation. That is, where the final variable is used, the equivalent of direct access to this constant is not required to be determined at run time. This is a bit like a macro replacement in C language.

So in the preceding code, because variable B is final decorated, it is treated as a compiler constant, so the variable B is replaced directly with its value where B is used. Access to variable D, however, needs to be done at run time through a link.

Presumably the difference should be understood, but be aware that the compiler will do this only if you know exactly what the final variable value is during compilation, such as the following code will not be optimized:

public class Test {public
  static void Main (string[] args) {
    String a = "Hello2"; 
    Final String B = Gethello ();
    String C = b + 2; 
    System.out.println ((A = = c));
  }
  public static String Gethello () {return
    "Hello";
  }
}

  The output of this piece of code is false.

2. Is the object content of the final decorated reference variable variable?

As mentioned above, when a reference variable that is final decorated can no longer point to another object after the assignment is initialized, does the content of the object that the reference variable point to is variable? Look at the following example:

public class Test {public
  static void Main (string[] args) {
    final MyClass MyClass = new MyClass ();
    System.out.println (++MYCLASS.I);
  }
Class MyClass {public
  int i = 0;
}

This code can be compiled smoothly and has output results of 1. This means that after the reference variable is final decorated, it cannot point to another object, but the contents of the object it points to are mutable.

3.final and Static

Many times it is easy to confuse the static with the final keyword, which is used to indicate that only one copy is saved, and the final function is to ensure that the variable is immutable. Look at the following example:

public class Test {public
  static void Main (string[] args) {
    MyClass myClass1 = new MyClass ();
    MyClass myClass2 = new MyClass ();
    System.out.println (myclass1.i);
    System.out.println (MYCLASS1.J);
    System.out.println (myclass2.i);
    System.out.println (MYCLASS2.J);
  }
Class MyClass {Public
  final double i = Math.random ();
  public static Double J = Math.random ();
}

When you run this code, you will find that the two J values printed each time are the same, while the value of I is different. From here you can see the difference between final and static variables.

4. Why is the external local variable used in the anonymous inner class only the final variable?

Please refer to this question in the previous posting "Java internal class details" in the explanation, here no longer repeat.

5. Questions relating to final parameters

On the Internet, "when you don't need to change an object variable as a parameter in a method, it's not appropriate to explicitly use final declaration to prevent unintended modification that affects variables outside the calling method."

Because whether the argument is a variable of the base data type or a variable of a reference type, using the final declaration does not achieve the effect described above.

Look at this example to be clear:

The above code seems to make people feel that after the final modification, you cannot change the value of the variable I in the method. As you can imagine, the method changevalue and the variable I in the Main method are not a variable at all, because Java parameter passing is a value pass, for the basic type of variable, the equivalent of a direct copy of the variable. So even if there is no final modification, the value of the variable I within the method will not affect the I of the method.

Look at the following code:

public class Test {public
  static void Main (string[] args) {
    MyClass MyClass = new MyClass ();
    StringBuffer buffer = new StringBuffer ("Hello");
    Myclass.changevalue (buffer);
    System.out.println (Buffer.tostring ());
  }
Class MyClass {
  void ChangeValue (final stringbuffer buffer) {
    buffer.append ("World");
  }

Running this code will find that the output is HelloWorld. Obviously, the final modification does not prevent the contents of the object in the ChangeValue from changing the buffer point.

Some people say that if the final removed, in case of changevalue in the buffer point to what to do with the other objects. A friend with this kind of idea can write the code by himself. What is the result, if the final is removed, and then the buffer in the ChangeValue points to other objects, it will not affect the buffer in the main method, because Java is using value transfer, For reference variables, the referenced value is passed, which means that both the argument and the formal parameter point to the same object, so having the parameter point back to another object has no effect on the argument.

The above content is the final keyword in Java detailed explanation, hope to be helpful to everybody.

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.