0
How can I use the Static in Java? and what is it for? What is its function?
0
How can I use the Static in Java? and what is it for? What is its function?
3
Drawn from here.
In Java, you can have 3 "Static" things: boot blocks, variables/methods and internal classes.
First you need to understand the following. Static is the same thing as "class", not "object". A class can have multiple objects. For example:
Carro vectra = new Carro();
Carro palio = new Carro();
Here we have only one class: "Car" But we have two objects: "Switch" and "Stick"
Now that you know the difference between class and object, it’s easier. Static is "class", that is, a Static variable of the Car class would have the same value for any object (Vectra, Palio, fusca, Ferrari...). So much so that you don’t even have to create objects to access them. It is usually used for counters, to see how many objects were created from the class, or to make global variables.
If you don’t put Static in the variables, they get a different copy for each object (which is more usual).
Boot blocks are blocks with things you want to run when the class is loaded into the virtual machine, which happens only once (it’s very little used, it’s mostly just to know it exists). For example:
static {
System.out.println("O classloader carregou essa classe!!");
}
And inner classes are classes within classes, which can also be Static (also little used, but know it exists). For example:
class Externa {
static class Interna {
}
}
Static utility: see its uses in class methods and fields Math Java, which is a class with no internal state.
Browser other questions tagged java static
You are not signed in. Login or sign up in order to post.