To define Global Variable you can make use of static Keyword
public class Example {
public static int a;
public static int b;
}
now you can access a and b from anywhere by calling
Example.a;
Example.b;
Answer from Abi on Stack OverflowTo define Global Variable you can make use of static Keyword
public class Example {
public static int a;
public static int b;
}
now you can access a and b from anywhere by calling
Example.a;
Example.b;
You don't. That's by design. You shouldn't do it even if you could.
That being said you could create a set of public static members in a class named Globals.
public class Globals {
public static int globalInt = 0;
///
}
but you really shouldn't :). Seriously .. don't do it.
There is no concept of global variable in the Java programming language. Instead, there are class and member attributes. Class attributes are marked with the static keyword, meaning that they can be accessed without instanciation, while member attributes are tied to an instance of a class.
Little example:
public class Person{
public static final int TOTAL_PERSONS;
private String firstname;
private String lastname;
public void setFirstname(String firstname){ ... }
...
}
With this class, I can use Person.TOTAL_PERSONS, but not Person.firstname. To get/set the first name (without mentionning getters/setters which you'll probably soon discover), you first need to create an instance of that class:
Person p = new Person();
p.setFirstname("foo");
Finally, note that it's possible to create what other languages refer to as global variables. For instance, you can use the Singleton pattern, but anyway, global variables shouldn't be used without valid reasons: check this page
Your question is a little confused since you refer to static/global in the title, and global/local in your question.
static variables are tied to a class, and you will have one instance per class.
classes can have member variables, and you will have one instance per instance of that class.
Note that this is complicated further if you have multiple classloaders. In this scenario you can have multiple class definitions loaded, and consequently, possible multiple static variables.
Videos
Static variables can (and should) be accessed using Class.Variable.
A static variable will always be available globally if they're public.
public class MyClass {
public static int X = 5;
}
Can be accessed everywhere the class is available using
MyClass.X
There's no actual 'global' keyword or anything, but it's close to its intention.
I think your book is (wrongly) using global as an easier way to describe a variable tied to a class.
For instance, take this class:
public class Apple {
private static int numberOfApples = 0;
public Apple() {
numberOfApples++;
System.out.println(numberOfApples);
}
}
Each time an Apple is created it will increment the numberOfApples variable and print it out. If you create two Apple objects then it will print:
1
2
The static variable in this case is globally shared by all Apple instances which may be what it means, but that is because it's tied to the class. This is different than a global variable in other languages.
edit: As others have mentioned, you can access a static variable without any instantiations of the class. If I made numberOfApples public and printed it out before creating any Apple instances then it would print 0. Similarly, after creating two Apple classes and then having both objects be destroyed, I could print numberOfApples and it would say 2.
While terminal and screen are in-scope everywhere, they are not automatically imported, and you have to reference them by the class that contains them.
For example, if you declared them in class Myclass, you would access them by eg.
MyClass.terminal.frobnicate();
Alternatively, though this is not standard practice in most cases, you can import them like so:
import static myPackage.MyClass.terminal;
Then you will be able to simply reference terminal without clarifying that you refer to MyClass's terminal, and not some other class's static field called terminal.
Instead of import you need a static import (The Static Import Java guide says, in part, The static import construct allows unqualified access to static members without inheriting from the type containing the static members). Something like (obviously with your entry-class)
import static com.foo.EntryClass.terminal;
import static com.foo.EntryClass.screen;
Your main method is static, so it can access only the static fields of the class directly. Otherwise, you need to create an instance of PlannerMain first, then you can access its fields. I.e.
public static void main(String[] args){
PlannerMain planner = new PlannerMain();
planner.frame = new JFrame("Land Planner");
planner.makeMap = new JButton("Make Map");
planner.makeMap.addActionListener(new makeMapListener());
...
}
Note that such initialization code is better put in a constructor method.
Btw the variables you refer to are not global. Right now you have as many distinct frame and makeMap as many instances of PlannerMain you create. They would only be "global" (or its closest equivalent in Java) if you declared them public static - in this case all PlannerMain instances would share the same frame and makeMap, and the external world would see them as well.
There are no global variables in Java in the meaning of variables which would be valid in the whole program.
There are
class variables: These are most similar to what are called "global" variables in other languages. They are declared inside a class with the
statickeyword. There is only one variable for the whole class. (If the class would be loaded again with another classloader, this new class would have new variables, of course.)They should be used prefixed with the class:
MyClass.varName. Inside of the class you also can omit the prefix, and you also could use them prefixed with an object of that type (but this is discouraged).instance (or object) variables: These are what you have in your example: anything declared inside a class (and outside of any method/constructor/block) without the
statickeyword is a instance variable. For each object of the containing class (which includes objects of any subclasses of this class) there is exactly one variable. (From the "state" view, one could say an object consists of all its instance variables + an identity.)They are used prefixed by an object (of the right type):
myObject.varName. Inside of non-static methods of this class you can use them unprefixed (this is then referring to the variables of the current object).local variables: These are all variables declared inside of a method or a constructor (or block). They exist once for each invocation of this method, and cease to exist after the method finished. They can only be accessed from inside this method/block, not from methods called from there.
Special cases of these are method/constructor parameters and
catch-block-parameters.array elements: Every element of an array is a variable of the same type. They can be used everywhere where one has a reference to this array (often in one of the other types of variables), using an index in brackets.
So, in your case you have object variables, and want to use them from a class method (static method). A class method has no current object, thus you have to qualify your variables with an object to use them. Depending on what you want, it may be useful to write it this way:
import java.awt.event.*;
import javax.swing.*;
public class PlannerMain {
JFrame frame;
JButton makeMap;
void initGUI() {
frame = new JFrame("Land Planner");
makeMap = new JButton("Make Map");
makeMap.addActionListener(new makeMapListener());
frame.setSize(580,550);
frame.setVisible(true);
}
public static void main(String[] args){
PlannerMain pm = new PlannerMain();
pm.initGUI();
}
}
forget Singletons, better is to use a static field. There are no other possibilities, only this two.
There is no such thing as a "global variable" in Java.
You could approach that behavior using a Singleton. A static field of a class will also give you similar behavior (though you ruled that option out in your question).
If you do not have multiple threads reading and writing the variable, and if psd should have one value across the entire application (which is implied by "global variable") I would indeed recommend making it static.
If each instance of the class it is declared in must have a separate copy of psd, I would instead suggest that fileItem5 must have a reference to the class psd is defined in, in order to be able to set it.
- No class is an island.
- There are no silver-bullets, at least its very true in programming.
- Premature optimisation is the root of all evil.
- In Java we don't have global variables. We only have class variables, instance variables, and method variables.
[Edit]
I am trying to explain here my last point. In fact, bringing the discussion, that is going-on in comments below, to the actual post.
First look at this, an SO thread of C#. There folks are also suggesting the same thing, which is,
- There are no global variables in C#". A variable is always locally-scoped. The fundamental unit of code is the class, and within a class you have fields, methods, and properties
- I would personally recommend erasing the phrase "global variable" from your vocabulary (this is in the comment section of the original question)
So, here we go.
retort: Classes are globally scoped, and thus all class variables are globally scoped. Hence should be called global.
counter-retort: Not all classes are globally scoped. A class can be package-private. Therefore, the static variables in there will not be visible outside the package. Hence, should not be called as global. Furthermore, classes can be nested, thus can be private as well and definitely can have some static variables but those wouldn't be called global.
retort: public classes are globally scoped, and thus all class variables are globally scoped.
counter-retort: Not exactly. I would like to move the previous argument here but on a variable level. No matter if the class itself is public. The variables in there can be protected, package-private and private. Hence, static variables will not be global in that case.
Now, if you like to call public static variable in public static class, as global then call it by any means. But consider this, when you create a new ClassLoader (as a child of the bootstrap ClassLoader) and load a class that you've already loaded. Then that results in a "very new copy of the class" -- complete with its own new set of statics. Very "un-global", indeed. However, we don't use the word global in Java because it tends to confuse the things and then we need to come with whole lot of explanations just to make everything clear. Folks rightly like to explain the feature of global variables in Java by static variables. There is no problem in that. If you have some problem/code in any other language and that is using global variables and you need to convert that code to Java, then you most likely make use of static variable as an alternative.
A couple of examples I like to render here
When I started Java, instructors like to explain the difference of passing object type variable and primitive variables. And they constantly use the term objects are
pass-by-reference, whereas primitives arepass-by-value. Students found this explanation quite confusing. So, we came up with the notion that everything in Java is pass-by-value. And we explain that for objects references are pass-by-value. It becomes much more clear and simple.Similarly, there are languages which support multiple-inheritance. But Java doesn't, again arguably speaking. But folks tend to explain that feature using
interfaces. They explain it by class implementing many interfaces, and call it multiple-inheritance. That's perfectly fine. But what the class, actually, receives by inheriting a number of interfaces. Frankly speaking, nothing. Why?. Because all the variables in interfaces are implicitly
public,finalandstatic, which apparently means those belongs to the class and anyone can access those. Now we can say that perhaps there would be someinner classin the interface, then the class implementing the interface will have it. But again that will bestaticimplicitly and will belong to the interface. Therefore, all what the class will get are methods. And don't forget just the definition and the contract which says, "the class implementing this interface must provide the implementation of all methods or declare itselfabstract". Hence, that class will only get responsibilities and nothing much. But that solves our problems in a brilliant way.
Bottom line
Therefore, we say
- There are no global variables in Java
- Java doesn't support multiple-inheritance, but something like that can be achieved by implementing multiple interfaces. And that really works
- There is nothing pass-by-reference in Java, but references are pass-by-value
Now I like to site few more places
- Java does not support global, universally accessible variables. You can get the same sorts of effects with classes that have static variables [Ref]
- However,
externin ObjectiveC is not an alternative to a class-scoped static variable in Java, in fact it is more like a global variable โฆ so use with caution. [Ref] - In place of global variables as in C/C++, Java allows variables in a class to be declared static [Ref]
- Furthermore, the overuse of static members can lead to problems similar to those experienced in languages like C and C++ that support global variables and global functions. [Ref]
All these are inferring one and the same idea. Which is Java doesn't support global variables.
Hell, I wrote that much. Sorry folks.
Performance doesn't matter. You want it as easy to read as possible.
I would do 2 as much as you can. When you really need constants and statics, make constants and statics.
For example, a null safe trim makes a good static method. New upping a StringTrimmer is silly. Putting if null then x else z in 1000 others is silly.