I searched the Internet but it was not clear to me what these reserved words mean and what features they have in a class:
- static
- final
I searched the Internet but it was not clear to me what these reserved words mean and what features they have in a class:
When using the reserved word static
the declaration of the constant must be done in the head of the class.
If we try to incorporate it into a method we will get an error.
This example does not compile:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
static final double PI = 3.1416;
}
}
but this one:
class Ideone
{
static final double PI = 3.1416;
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(Ideone.PI);
}
}
That's why within the main
method, since this is a class method and it has incorporated static
in its declaration, we can not declare class constants.
But final
if it can be used within methods also also within the main
method.
Example: final double PI = 3.1416;
is valid within a method.
Also final double PI = 3.1416;
can be used to access some data that you know can not be modified in theory once declared / initialized with a value.
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
final double PI = 3.1416;
}
}
Static members can call them without having to create an instance of it, for example when you use new MiClase
... miClase.a
. Now you could do MyClass.a without having to use or create an instance of it.
class MiClass{
static int a; // Puedes acceder sin crear una instancia por ejemplo MiClass.a
final double PI = 3.1416
}
By making a class static
this can be called, so you can use your methods for example without having to create an instance of it, for example when you use new MiClase
... miClase.miMetodo();
. Now you could do MiClaseEstatica.miMetodo();
without having to use or create an instance of it.
Java has no way to make a static top-level class can do something like the following:
public final class MiClaseEstatica {
static public int sumar (int a, int b){
return a + b;
}
}
//...
System.out.println(MiClaseEstatica.sumar(3, 2));
Here we make use of a static call without having to create an instance to access, for example, some method of the class.
It would come to save something like:
public MiClase miClase = new MiClase();
System.out.println(MiClase.sumar(3, 2));
You may be interested in reading this question / answer
Internal classes can be declared static.
a .class will be created for each of these internal classes.
public class Obj {
private int data1;
private String data2;
public Obj(int data1, String data2) {
this.data1 = data1;
this.data2 = data2;
}
private static class ObjComp implements Comparator<Obj> {
@Override
public int compare(Obj obj1, Obj obj2) {
return obj2.data1 - obj1.data1;
}
}
}
You can also create code blocks as static to be executed when the class is loaded.
is usually known as (static initializer block) if it is not explicitly declared the JIT compiler (just-in-time) combines all the static fields in a block and executes them during the loading of classes.
public class Obj {
private static int data1;
static {
data1 = 10;
}
The initialization blocks can be replaced by static methods as in the following example you can see:
public class Obj {
private static int data1 = inicializacionDeCampo();
private static int inicializacionDeCampo() {
return 10;
}
}
this initialization logic of class variables static
can be applied without the need to include it in its class constructor.
static allows access to methods, class variables without the need to instantiate an object of the class in question, is usually used for example for the creation of utility classes. Java has several of these, such as:
Then members static
belong to the class instead of a specific instance, this is key to understand the following faster:
There will only be one field static
even if thousands of instances of the class were created, and even more to have found even if "there is no instance" of it.
With what that field will be shared by all instances.
This, if analyzed a bit, makes a lot of sense, both for the foregoing and as applied to static methods. When it says that they can not refer to members of an instance, because if so, which instance is being referred to when they all share the same static field or method.
That is not the same as accessing through a specific instance.
Example:
public class Obj {
private static boolean data3;
private boolean data4Instancia;
public static void main(String[] args) {
data3 = true; //un método estático accediendo al campo estático
Obj instancia = new Obj();
instancia.data4Instancia = true; //un método estático acceda a un campo no estático de una instancia especifica, aquí le decimos de alguna manera oye esta es la instancia a la que quiero acceder.
}
All this makes sense because the values, fields, non-static methods depend on the creation of instances of the class.
When it is said that only one static field will exist, it is true halfway, but depending on the level at which it is being explained it may be more valid or less valid, for example it can be one by Class Loader
by or thread (thread) , among other cases, I only mention it so that it is found in a certain way, in case you want to delve into it.
Modifiers static
and final
have completely different contexts.
static
The static
modifier implies that something is defined in the general context, not in a context of an object. Without this modifier, variables, classes or fields always exist in the context of an instance of a particular object.
static
are global variables. static
are global functions. static
function as normal classes, they can be instantiated from outside the class containing them, and (obviously) do not have the same access to variables and methods of objects instantiated from the container class. final
Final in general means immutable. There are two main uses:
Variables declared as final can not be overwritten. That does not mean that an object that was assigned to a final variable can not be modified in its fields or by its methods, it just means that the reference of this variable to this same object will never change.
Classes declared as final can not be used as superclasses. String
for example is a class defined as final, so it is not possible to declare a MegaString extends String
- Java does not allow it. Similarly, methods declared as final can not be overwritten by @Override.
Common uses of static
Constants (in combination with final
):
public static final int RESULT_CANCELED=0;
Singletons (objects of which a single instance should be used):
public static final SecureRandom sr = SecureRandom();
Global variables:
private static int numLusers=0;
Global methods:
public static Luser newInstance(){
numLusers++;
return new Luser();
}
Public internal classes
public class Almacenamiento{
public static class AlmacenamientoCreateHelper{
...
}
...
}
But if an internal class declared static
does not have direct access to methods and fields of the outer class, which is the advantage of declaring an inner class like this?
It's an organizational issue and there's probably a variety of opinions on that. I personally prefer to group classes by packages to organize them, however there is an obvious advantage: If I maintain classes that are highly dependent on their code, keeping them in the same file helps a lot in avoiding errors by combining classes of different versions, if I use .java
containing external and internal class, I can always be sure that I have compatible versions.
Common uses of final
Constants (in combination with static
)
public static final String AUTHORITY="com.snolde.app";
"Value Objects" fields used in concurrency contexts.
public class LuserVO{
public final String uname;
public final int uid;
public final Token authToken;
public LuserVO(String uname, int uid, Token auth);
}
Local variables for use in anonymous classes:
final Socket sock = server.accept();
Task t = new Task(new Runnable(){
@Override
public void run(){
InputStream is = sock.getInputstream();
...
}
});
Final classes that should not be extended:
public final class AuthToken{
...
public boolean hasPrivilege(int pId);
}
// No es posible de crear una clase como esa para pasarlo a un método que acepta AuthToken:
WeonAuthToken extends AuthToken{
@Override
public boolean hasPrivilege(int pId){ return true; }
}
Methods that should not be overwritten:
protected final void onAgregado(Contexto contexto, Node padre){
// aqui tengo código que esta llamado por otra clase de mi biblioteca
// que es importante para el funcionamiento, y quiero evitar
// cambios en el flujo. Después ofrezco un gancho para código
// extendido.
}
protected abstract void onDespuesAgregado(Contexto contexto, Node padre);
The static keyword can be used in 4 scenarios:
Let's first look at static variables and static methods.
Static variable
Static method
It is a method that belongs to the class and not to the object (instance) A Static method can only access static data. Can not access non-static data (instance variables) unless have / create an instance of the class. A static method can call other static methods and can not call a method not static of it unless you have / create an instance of the class. A static method can be accessed directly by the name of the class and does not need any objects Syntax: Class.methodName () A Static method can not refer to this or super keywords in any case
Static class
Java also has "nested static classes". A static nested class is one that does not implicitly imply a reference to an instance of the external class.
Static nested classes can have instance methods and static methods.
There is no such thing as a higher-level static class in Java.
The final keyword is used in several different contexts to define an entity that can not be changed later.
A final class can not be subclassified. This is done for reasons of safety and efficiency. Therefore, many of the standard Java library classes are final
, for example java.lang.System
and java.lang.String
. All methods of a class final
are implicitly final
.
A method declared as final
can not be overwritten by subclasses. This is used to avoid unexpected behavior of a subclass that alters a method that may be crucial for the function or consistency of the class.
A variable final
can only be initialized once, either through an initializer or an assignment declaration. It does not need to be initialized at the point of the declaration: this is called a final blank variable ( blank final
). An instance variable% co_of blank% of a class must be definitively assigned to the end of each constructor of the class in which it is declared; Similarly, a final static blank variable must be definitively assigned to a static initializer of the class in which it is declared; Otherwise, a compile-time error will occur in both cases.
There is a answer in SO by @Ashish
The Constants are declared as follows:
public static final String CONSTANTE = "VALOR";
static - > indicates that it is accessible at the Class level and does not need an instance of it to be used.
final - > indicates that the value once declared can not be changed.
example
public class Clase1
{
public static final String CONSTANTE = "VALOR";
}
public class Clase2 {
public static void main (String[]agr)
{
System.out.println(Clase1.CONSTANTE);
}
}
Sometimes they make the definition of certain keywords complicated, I try to be the simplest.
static:
make a property or method of the class, is own class, this means, if you have the class Dog, and you have a property color = "negro"
all dogs that you create with this class will be color = negro
, if in a moment you change the value to color = "azul"
, now all the dog objects that you created with black color, will be blue, because it is class-specific.
Perro.color = "negro";
// the public static attribute of the Dog class is modified
Perro perro1 = new Perro();
Perro perro2= new Perro();
// se crearon 2 perro con atributo color = "negro"
System.out.println(perro1.color); //imprime "negro"
System.out.println(perro2.color); //imprime "negro"
Perro.color = "azul"; // se modifica el atributo static
System.out.println(perro1.color); //imprime "azul"
System.out.println(perro2.color); //imprime "azul"
The change is due to the fact that it is an attribute of the class (species) not of the object, if changing an attribute of the class, all the objects of that class are "affected"
In the methods: allows you to call the method directly without the need for an object created. In the same case of the dog, if you have a correr()
method and it is not static, you could only call it like that
Perro perro = new Perro();
perro.correr();// <- lo llamas desde el objeto perro creado.
If it were static
, it is not necessary to have an object created, just call the class
Perro.correr() //<-- se llama desde la propia clase porque es static, propia de la clase
final
The type of variable Final
, are simpler, they only make the attribute or what is defined with this word, can not be modified. It is its final value, it serves mostly when you want to declare CONSTANTS, values that never go to change.
Note: The static
variables facilitate many things, because when you create elements with this value, they can be easily accessible only from the class. the "final" attribute allows only to make sure that the element is immutable, it can not be modified. the "static final" attributes allow both, are accessible from anywhere only from your Class, and are immutable.
public static final double VALOR_PI = 3.1415926;
// por convención las contantes deben ir todas en mayusculas, esto quiere decir, todas los atributos del tipo "final"
The static do not need to instantiate the class ... I mean = new Clase()
to call them, it is simply to call the method for example: clase.metodoStatic();
, without requiring the instance Clase clase = new Clase()
, within these you can only use more static methods, none of instance.
The Final class means that they can not have inheritance .
And that is all the difference, the rest is pure straw ... more information.
I hope I can help you, regards.