I have searched the Internet but it has not been very clear to me what these reserved words mean and what functionalities they have in a class:
- static
- final
I have searched the Internet but it has not been very clear to me what these reserved words mean and what functionalities they have in a class:
When using the reserved word
static
, the declaration of the constant must be made in the class header.If we try to incorporate it into a method we will get an error.
This example does not compile:
but this one yes:
That is why within the method
main
, since this is a class method and it is incorporatedstatic
in its declaration, we cannot declare class constants.But
final
yes, it can be used inside methods as well as inside the methodmain
.Example:
final double PI = 3.1416;
it is valid within a method.It can also
final double PI = 3.1416;
be used to access data that you know cannot be modified in theory once it is declared/initialized with a value.Static members can be called without having to create an instance of it, for example when you use
new MiClase
...miClase.a
. Now you could make MyClass.a without having to use or create an instance of it.By making a class
static
it can be called, that is you can use for example its methods without having to create an instance of it, for example when you usenew MiClase
...miClase.miMetodo();
. Now you could doMiClaseEstatica.miMetodo();
without having to use or create an instance of it.Java has no way to make a static top level class you can do something like the following:
Here we make use of a static call without the need to create an instance to access, for example, a method of the class.
It would save something like:
You may be interested in reading this question/answer
Inner classes can be declared static.
a .class will be created for each of these inner classes.
you can also create code blocks as static so that they are executed when the class is loaded.
they are usually known as (static initializer block) if it is not explicitly declared the JIT (just-in-time) compiler combines all the static fields in a block and executes them during class loading.
The initialization blocks can be replaced by static methods as in the following example you can see:
You can apply this initialization logic to class variables
static
without needing to include it in your class constructor.static allows access to methods, class variables without the need to instantiate an object of the class in question, it is often used for example for the creation of utility classes. Java has several of these, such as:
So the members
static
belong to the class instead of a specific instance, this is key to understand the following faster:Only one field will exist
static
even if thousands of instances of the class were created, and even more to have found even if no instance of it "exists".So that field will be shared by all instances.
This, if analyzed a bit, makes a lot of sense, both for the above and when applied to static methods. When it is said that they cannot refer to members of an instance, because if so, which instance is it referring to when they all share the same static field or method.
Which is not the same as accessing through a specific instance.
Example:
All this makes sense because the values, fields, methods NOT static depend on the creation of instances of the class.
When it is said that there will only be one static field, it is half true, but depending on the level at which it is being explained, it can be more valid or less valid, for example it can be one per
Class Loader
per or the thread (thread) , among other cases, I only mention it so that it can be found in a certain way, in case you want to go deeper into it.https://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html
static
The and modifiersfinal
have completely different contexts.static
The modifier
static
implies that something is defined in the general context, not in an object context. 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
work like normal classes, they can be called from outside the containing class and (obviously) they don't have the same access to variables and methods of called objects of the containing class.final
Final in general means immutable. There are two main uses:
Variables declared as final cannot be overwritten. That doesn't mean that an object that was assigned to a final variable can't be modified in its fields or by its methods, it just means that the reference from this variable to this same object will never change.
Classes declared as final cannot be used as superclasses.
String
for example it is a class defined as final, so it is not possible to declare oneMegaString extends String
- Java does not allow it. Similarly, methods declared final cannot be overridden by @Override.Common uses of
static
Constants (in combination with
final
):public static final int RESULT_CANCELED=0;
Singletons (objects that should only be used in one instance):
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
But if a declared inner class
static
does not have direct access to methods and fields of the outer class, what is the advantage of declaring such an inner class?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 keep classes that are highly dependent on their code, keeping them in the same file helps a lot in avoiding errors by combining classes from different versions, if I use the
.java
one that contains outer and inner class, I can always be sure that I have the compatible versions.Common uses of
final
Constants (in combination with
static
)"Value Objects" fields used in concurrency contexts.
Local variables for use in anonymous classes:
Final classes that should not be extended:
Methods that should not be overridden:
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. You can't access non-static data (instance variables) unless you have/create an instance of the class. A static method can call other static methods, and you can't call a non-static method of it unless you have/create an instance of the class. A static method can be accessed directly by the class name and does not need any object Syntax: Class.methodName() A static method cannot refer to this or super keywords in any case
static class
Java also has "static nested classes", A static nested class is one that does not implicitly imply a reference to an instance of the outer class.
Static nested classes can have instance methods and static methods.
There is no such thing as a top level static class in Java.
A final class cannot be subclassed. This is done for security and efficiency reasons. Consequently, many of the Java standard library classes are
final
, for examplejava.lang.System
andjava.lang.String
. All methods of a classfinal
are implicitlyfinal
.A method declared as
final
cannot be overridden by subclasses. This is used to prevent unexpected behavior of a subclass that alters a method that may be crucial to the function or consistency of the class.A variable
final
can only be initialized once, either through an initializer or an assignment statement. It does not need to be initialized at the point of the declaration: this is called a trailing blank (blank final
) variable.final
A blank instance variable of a class must definitely be assigned to the end of each constructor of the class in which it is declared; Similarly, a final blank static variable must definitely be assigned in a static initializer of the class in which it is declared; Otherwise, a compile-time error will occur in both cases.There is an answer on SO by @Ashish
Sometimes they make the definition of certain keywords complicated, I will try to be as simple as possible.
static :
make a property or method of the class, be proper to the class, this means, if you have the class Dog, and you have a property,
color = "negro"
all the dog objects that you create with this class will be fromcolor = negro
, if in a moment you change the value tocolor = "azul"
, now all the dog objects that you created with black will be blue, because it is class-specific.Perro.color = "negro";
// the public static String attribute of the Dog class is modifiedThe change is due to the fact that it is an attribute of the class (species) not of the object, if you change an attribute of the class, all the objects of that class are "affected"
In the methods: it allows you to call the method directly without the need for an object created. In the same case of the dog, if it has a method
correr()
and it is not static, you could only call it like thisIf it were
static
, you don't need to have an object created, just call from the classfinal
The variable types
Final
are simpler, they only make the attribute or what is defined with this word cannot be modified. It is its final value, it is mostly used when you want to declare CONSTANTS, values that will never change.Note: variables
static
make a lot of things easier, because when you create elements with this value, they can be easily accessible only from the class. the "final" attribute only allows you to make sure that the element is immutable, it cannot be modified. "static final" attributes allow both, are accessible from anywhere only from your Class, and are immutable.Constants are declared like this:
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 cannot be changed.
example
The static does not need to instantiate the class... that
= new Clase()
is, to call them, it is simply to call the method for example:clase.metodoStatic();
, without requiring the instanceClase clase = new Clase()
, within these you can only use more static methods, none of instance.The Final class means that they cannot have inheritance .
And that's all the difference, the rest is pure straw... more information.
I hope I can help you, greetings.