What is the use of a static or final variable in java?

Asked

Viewed 96,047 times

38

What is the difference of the declaration private static int var_nome for private final int var_nome for private int var_nome? How these statements can influence my algorithm?

  • 2

    Nothing against the answer of utluiz, it is very good. But you wanted to know other things about the subject? I should have asked the question and everyone who answered it would have the opportunity to meet all their needs. It’s hard to guess that you want more than you posted.

  • His reply was quite complete right, he explained everything about it. In addition to the context and many other things, but I understand your complaint and do not know what would be the best answer to the question, I will evaluate later, ok?

3 answers

57


Response of the type "Learning by Examples".

Visibility Modifiers

The word-reserved private modifies how other classes in your program can see a class or class attribute.

Classes

For classes, we can have modifiers:

public

All the rest see.

public class MinhaClasse { ... }

private

Only classes in the same source file see. Use this when the implementation serves some internal algorithm of the main class.

public class MinhaClasse {
    private class MinhaClasseInternaPrivada { ... }
}
private class MinhaClassePrivada { ... }

Note: each file .java may have only one public class.

(default)

Only classes in the same source file or in the same package (package) see. Use when the implementation is only for your library or for a particular part of your program.

class MinhaClasse { ... }

Methods

Methods may have the following visibility modifiers:

public

All classes see it, as long as they see the class too.

public class MinhaClasse {
    public void meuMetodo() { }
}

private

Only classes in the same source file see. Use this when the method is only done for use of other public class methods.

public class MinhaClasse {
    private void meuMetodoSecreto() { }
    public void meuMetodoPublico() {
        meuMetodoSecreto();
    }
}

Private methods cannot be overwritten.

protected

Protected methods can be viewed by classes in the same package or by subclasses.

public class MinhaClasse {
    protected void meuMetodo() { }
}

Use this if you are going to make some kind of library that allows another developer to extend their classes and then use these special methods, which should not be called by other classes that use your library.

(default)

Methods without modifier can be seen only by classes in the same package.

public class MinhaClasse {
    void meuMetodo() { }
}

Use this when a method is only used by the classes that make up a part of your program.

Attributes

Attributes work almost like methods.

public

All classes see it, as long as they see the class too.

public class MinhaClasse {
    public int atributo = 1;
}

It is bad practice to have int attributes, unless they are "constant" or you want to simulate structures like the C language.

private

Only classes in the same source file see. Try to leave all your attributes private and give the chained access to them through getters and setters.

public class MinhaClasse {
    private int atributo = 1;
    public int getAtributo() {
        return atributo;
    }
    public void setAtributo(int atributo) {
        this.atributo = atributo;
    }
}

protected

Protected attributes can be viewed by classes in the same package or subclasses.

public class MinhaClasse {
    protected int atributo = 1;
}

(default)

Attributes without modifier can be seen only by classes in the same package.

public class MinhaClasse {
    int atributo = 1;
}

Modifier final

Used in various contexts: classes, methods, attributes and variables.

Classes final

A class with this modifier cannot be extended, that is, it cannot have classes inherited from it.

This is important to ensure that a particular implementation does not have its behavior modified. This has a lot to do with immutability.

Basic types of Java like String and Integer sane final because it is hoped that the content cannot be modified. The problem is that your someone could create a subclass of String, this implementation could become changeable. A String changeable would be chaos on earth for implementations, as various assumptions that developers use on a day-to-day basis would simply be undone.

public final class String
     implements java.io.Serializable, Comparable<String>, CharSequence
{ ... }

Method final

It is a method that cannot be overwritten in the subclasses.

Use to ensure that a particular algorithm cannot be modified by subclasses.

Example:

class ChessAlgorithm {
    enum ChessPlayer { WHITE, BLACK }
    ...
    final ChessPlayer getFirstPlayer() {
        return ChessPlayer.WHITE;
    }
    ...
}

Attribute final

An attribute final of a class can have its value assigned only once, either in the declaration itself or in the constructor.

public class MinhaClasse {
    final int x = 1;
    final int y;

    public MinhaClasse(int y) {
        this.y = y;
    }
}

Use this to ensure that an object value or reference will not change. We return to immutability.

If you have an algorithm that uses this variable, you can store calculated values without the worry of changing the value.

Example:

public class MinhaClasse {
    final Cliente cliente;
    final BigDecimal saldo;

    public MinhaClasse(Cliente cliente) {

        this.cliente = cliente;

        //sabemos que saldo não muda
        this.saldo = cliente.chamarOperacaoComplexaQueCalculaOSaldo();

    }

    public BigDecimal getSaldoCliente() {
        //não precisa mais recalcular toda vez
        return saldo;
    }
}

Variables final

Use to ensure that you are not improperly modifying the value.

final boolean a = lerInputUsuario();
final boolean b = lerInputUsuario();
...
if (a = b) //ops!!!

In the above code, suppose the developer wanted to compare the values of a and b, but lacked an equal sign. Without the final, there would be an undue assignment and the result would be the boolean value of b. But how n is final, compiler will accuse an error. We have just prevented an involuntary assignment!

Internal Threads and Classes

Another advantage of variables and attributes final is able to use them in internal classes, a technique widely used in Threads.

public class MinhaClasse {

    public void executarEmParalelo(final int limite, final Processamento proc) {
        Thread t = new Thread() {
            public void run() {
                for (int i = 0; i < limite; i++) {
                    proc.executar();
                }
            }
        };
        t.start();
    }
}

Modifier static

It changes the scope of a method or attribute. With the static, instead of them belonging to the object instance, they belong to the class.

The modifier can also be applied to classes, as we will see below.

Methods static

The methods static can be called without an instance. They are great as utilities.

public final class Integer extends Number implements Comparable<Integer> {
    public static Integer valueOf(String s, int radix) throws NumberFormatException {
        return new Integer(parseInt(s,radix));
    }
}

You can call it that:

Integer valor = Integer.valueOf("FF", 16);

Static methods cannot access instance variables.

public class MinhaClasse {
    int valor = 1;
    public static int estatico() {
        return valor; //erro de compilação aqui!!!
    }
}

Attributes static

The attributes static have the same value for all instances of an object (within the same JVM, within the same Classloader).

public class MinhaClasse {
    static int valorGlobal = 1;
    public static int getValorGlobal() {
        return valorGlobal;
    }
}

So here’s what we can do:

MinhaClasse c1 = new MinhaClasse();
MinhaClasse c2 = new MinhaClasse();
MinhaClasse.valorGlobal = 2;
System.out.println(c1); //imprime 2
System.out.println(c2); //imprime 2

Classes static

Classes static are classes declared within another class that can be used without the need for an instance.

public class MinhaClasse {
    public static classe ClasseInterna { }
}

So we can access it like this:

MinhaClasse.ClasseInterna instancia = new MinhaClasse.ClasseInterna();

Putting it all together

Now that we understand what each thing does individually, let’s go to a practical application.

Singleton Design Standard

Problem: I want to ensure a single instance of an object in my program.

Solution:

public class MinhaClasse {
    private static MinhaClasse instancia;
    public static MinhaClasse getInstancia() {
        if (instancia == null) {
            intancia = new MinhaClasse();
        } 
        return instancia;
    }
}

Use:

MinhaClasse instancia = MinhaClasse.getInstancia();

This will return the same value on all calls.

Basically, what we did was this:

  1. Create an attribute called instancia that only the MinhaClasse you can see (private) and always contains the same value (static).
  2. Create a method that can be called directly by the class, without needing the instance (static).
  3. Then, the static method returns the static value, which will always be the same.
  • 2

    Great explanation Chief, it helped a lot!

  • 1

    I think you should fix it: "It is bad practice to have int attributes, unless they are "constant" or you want to simulate structures like the C language." - There have been people who didn’t understand exactly what you wanted: http://answall.com/q/132272/132 - I think you meant "public attributes" instead of "int attributes". Correct?

22

How are you using private I will understand that you are talking about fields of a class and not variables.

A static field is the one who is available in a unique form class for the entire application. It is not bound to an instance of the class. It belongs to the class itself and is shared by all instances (objects) of this class created while running the application.

A final field is the one who cannot have its contents changed after initializing. We can understand it as a read-only field. The field value is initialized for each instance of the class at the time of its creation and obviously each object can have this field with different value. The content can be initialized by a constructor or by direct assignment. If the field contains a reference, only the reference cannot be modified, the contents of the referenced object can. Therefore final does not in itself guarantee the immutability of the object.

As these fields are, in the example, properly declared as private, a modification, or even access outside the class can only happen through access methods, for example getNome and setNome.

You may have a field statement that is static and final at the same time. In this case we have a constant field. Since you have a unique value for the entire application and it cannot be modified. With static final the Java compiler can replace the use of the field with its compile-time value by achieving an optimization.

When even static nor final are present in the field declaration, it has its individualized value for each instance of the class and its value can be modified.

There are static methods that can access static fields. Static methods can serve as accessors to a static private field. but if beyond static the field is final, you can usually leave the field publicly exposed. At least if you’re sure that his semantics are a real constant and will never be changed. A good example of final static field with constancy semantics is the PI. An example of nonconstancy would be the MaxThreads (one day it may change, so it’s not really constant).

  • How a static field can be private?

  • In this case, it is only within the class that it is accessible. No one quoted, but we can have static methods as well. So an attribute static final can be accessed from inside static methods and instance methods as well.

  • @Patrick And what’s the problem? I can’t guarantee that Java allows this (it would be too weird not to), but there’s no reason not to. Only members of the class can access it. It seems to me a common pattern in various situations.

  • Java allows private static fields yes.

  • 1

    @Piovezan I was pretty sure, if I didn’t allow it, I’d look for a professional killer to go after Gosling :)

  • If only class members can access it, what’s the point of putting static?

  • @Patrick, it’s very common to use attributes static final for settings. For example: https://github.com/TheFinestArtist/SimpleYouTubePlayer/blob/master/src/com/thefinestartist/simpleyoutubeplayer/YouTubePlayerActivity.java

  • 2

    @Patrick accessibility has nothing to do with field property. They are different concepts. A static method may need a state for its execution. A method may not have been. Where will you put the state? In a field. If the method is static, you will probably want a static state (shared, single).

  • public class Cachorro { private static final String NOME_PADRAO = "Totó"; private String nome; public Cachorro() { this.nome = NOME_PADRAO; } public Cachorro(String nome) { this.nome = nome; } public String getNome() { return this.nome; } }

Show 4 more comments

15

The modifier final in variables means that you cannot assign value twice to the variable.

The modifier static means that the variable belongs to the class, not to the object; this means that all instances of a class see the same variable, and if one of them changes the value, it will reflect in all other instances.

To declare a constant use the two modifiers because the same value will be seen by all instances of the class (static) and can never be modified after initialized (final).

Variables that are neither static nor final are normal attributes of an object, and therefore vary from object to object, for example:

public class Pessoa {
   private String nome; // será diferente para cada objeto
   ...
}

Adapted from a topic from Javafree.

  • Perfect! Beautiful answer!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.