Deep Java Final_java

Source: Internet
Author: User

The Java keyword Final is used to modify data, methods, or classes, usually meaning "immutable", where data cannot be changed, methods cannot be overridden, and classes cannot be inherited. There are two general reasons for final adoption: design and efficiency. As the Java version is updated, some of the efficiency problems can be left to the compiler and JVM to handle. Therefore, it is less important to use final to solve the problem of efficiency.

The final modifier is mostly used for basic data type (primitive) fields or fields of immutable (immutable) classes (if all method methods in a class do not change their objects, this class is immutable). A string is an immutable class).

"Final Data"

The final keyword uses modified data for two main scenarios:

1. Compile-time constants

2. Runtime initialization value

For a compile-time constant, a field that is both final and static (by convention, compile-time constants are all named with uppercase letters and underlined to separate each word), and it occupies only a single storage space that cannot be changed. The compiler can substitute a compile-time constant for any calculation that might be used, that is, you can perform a calculation at compile time, which relatively eases the run-time load. A compile-time constant must be assigned a value (not necessarily a basic type) when it is defined.

Runtime-initialized values, for the base type, final makes the value immutable, and for an object reference, final makes the reference immutable, that is, it cannot be changed to point to another object, however, the object itself can be modified (applicable to arrays, and arrays are objects).

Copy Code code as follows:

public class javafinaldata{

private static final String TESTD = "Test";
public static final String teste = "Test";
public static final string[] Testf = {"1", "2"}; Non-basic type
private static final string[] Testg = new string[2];

public static void Main (String args[]) {
Final int testa = 1;
Final String testb = "Test";
Final int[] Testc = {1,1,2,};
System.out.println (testc[1]);
TESTC[1] = 123;
System.out.println (testc[1]);
}
}

"Unassigned Final Field"

Java allows you to generate unassigned final fields, but you must assign values to the final field at the definition of the domain or in each constructor (how many constructors must be assigned several times) to ensure that it is initialized before use. In this way, final application can be more flexible, in the same class, according to different objects to give different values, but also maintain the immutable characteristics.

Copy Code code as follows:

public class javablankfinal{
private final int blank;

Public javablankfinal () {
blank = 2011;
}

public javablankfinal (int temp) {
blank = 2012;
}

Public javablankfinal (String temp) {
blank = 2014;
}

public static void Main (String args[]) {
New Javablankfinal ();
}
}

"Final Method"

There are two reasons for using the final method: locking the method, preventing the method from being overwritten, ensuring that the method behaves in the inheritance, and converting the method call to an inline call (inlining) to reduce the overhead of the method invocation. However, in the most recent release, the JVM was able to optimize itself, so there was no need to use the final method to address efficiency issues.

With regard to the final method, it is also important to note that all private methods in a class are implicitly specified as final methods (or they can be combined with final modification, but meaningless). When you try to overwrite a private method, the compiler does not make an error, but in fact you do not overwrite the method, only a new method is generated. Because a private method cannot be accessed by an external class, it cannot be overwritten.

Use @override annotations to prevent the above problems. As the program shows:

Copy Code code as follows:

Class finalfunction{
private void Finalfunctiona () {
System.out.println ("Finalfunctiona");
}

Private final void finalfunctionb () {
System.out.println ("finalfunctionb");
}

final void Finalfunctionc () {
System.out.println ("Finalfunctionc");
}

void Functiond () {}
}

Class Overridefinalfunction extends finalfunction{
   //@Override    Add @override annotations to identify whether it is override
    public void Finalfunctiona () {               
        System.out.println ("Override Finalfunctiona");
   }

    public final void Finalfunctionb () {
        System.out.println ("Override Finalfunctionb");
   }

   //final void Finalfunctionc () {}  //cannot override the final method from Finalfunction

    @Override   
    void Functiond () {}// The true override method
}

public class Javafinalfunction extends finalfunction{
public static void Main (String args[]) {
Finalfunction ff = new finalfunction ();
Ff.finalfunctiona (); Cannot invoke Private method
Ff.finalfunctionb ();

Overridefinalfunction off = new Overridefinalfunction ();
Off.finalfunctiona (); Public method
Off.finalfunctionb ();
}
}


"Final Class"

The final class is typically used for design reasons, and the class is not allowed to be inherited. This ensures that the behavior of the class does not change and may also avoid some security risks. All methods in the final class are implicitly specified as the final method and cannot be overwritten (because the final class prohibits inheritance and cannot overwrite methods in its class). In the Java Core API, there are many examples of final application, such as java.lang.String. Specifies the final method to prevent overwriting length () for the string class.

For final domains, a domain in a class does not automatically become the final domain, even if a class is declared final.

Copy Code code as follows:

Final class finalclass{
int testa = 2011;
}
Class Extendfinalclassextends finalclass{}//can not extendthe final class Finalclass

public class javafinalclass{
public static void Main (String args[]) {
Finalclass FC = new Finalclass ();
System.out.println (Fc.testa);
Fc.testa = 2012;
System.out.println (Fc.testa);
}
}

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.