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?
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?
57
Response of the type "Learning by Examples".
The word-reserved private
modifies how other classes in your program can see a class or class attribute.
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.
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 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.
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 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;
}
Attributes without modifier can be seen only by classes in the same package.
public class MinhaClasse {
int atributo = 1;
}
final
Used in various contexts: classes, methods, attributes and variables.
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
{ ... }
final
It is a method that cannot be overwritten in the subclasses.
Use to ensure that a particular algorithm cannot be modified by subclasses.
class ChessAlgorithm {
enum ChessPlayer { WHITE, BLACK }
...
final ChessPlayer getFirstPlayer() {
return ChessPlayer.WHITE;
}
...
}
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;
}
}
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!
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();
}
}
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.
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!!!
}
}
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
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();
Now that we understand what each thing does individually, let’s go to a practical application.
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:
instancia
that only the MinhaClasse
you can see (private
) and always contains the same value (static
).static
).Great explanation Chief, it helped a lot!
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.
@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
@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; } }
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 java oop variables variable-declaration
You are not signed in. Login or sign up in order to post.
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.
– Maniero
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?
– Nicolas Bontempo