The difference between the static keyword and the final keyword in Java

  • 2020-04-01 01:33:58
  • OfStack

The static

1. In the class, the static attribute is called the static attribute. Shared by all objects of this class, in a static storage area, all objects of this class can access and access the same variable. You can use it as a counter to count how many different types of objects have been created.

2. In the class, the method with static modification is static method. In the static method, non-static properties and methods cannot be accessed, but in the non-static method, static methods and properties can be accessed; Static method polymorphic invalidation, this cannot be used.

Since static properties and methods belong to all objects in the class, they can be accessed using the class name.

4. Static also modifies a block of code that is executed once and only once during class loading.

final

(1) classes with final tags cannot be inherited


final class T{}
class TT extends T{}//Error, final class cannot be inherited

(2) methods with final tags cannot be subclassed


class T{
    public final void function(){}
}
class TT extends T{
    public void function(){}//Error, final method cannot be subclassed
} 

(3) the local variable of the final tag is a constant & PI;              

final int x=10;
x=3//Error, local variable of final tag is constant and cannot be assigned

  (4) a finally-tagged member variable must be assigned at the same time as being declared, or must be displayed in the constructor of the class (there is no default for instance variables), before it can be used.

Such as:


class Test{
final int x=10;//Declare and assign values
}
//or
class Test{
    final int x;
    Test(){
     x=10;

}
 

(5) the built-in class defined in the method can only access the local variables of the final type within the method, and the local variables defined with final are equivalent to a constant whose life cycle is longer than the life cycle of the method running.

(6) it is also possible to define a parameter as final, which limits the value range of the parameter to be modified in the method.

There are many classes of final type in Java :String,Math, and so on.


Related articles: