Let's say i have a class, and I made only one instance of it and i don't need more than that.
Should i just make the class static ? (not the class itself but the functions and the variables).
In the example below should i make the class static if i won't make more than one instance of it ?
public class Foo {
int num1;
int num2;
public void func() {
// Something in here
}
}
public static void main(String[] args) {
Foo bar = new Foo(); //I don't need more than one instance of that class.
}
If your class has no state, say:
class NoState {
static int sum(int i1, int i2) { return i1 + i2; }
}
then it makes sense to use static methods.
If you must ensure that there is only one instance of your class, then you could use a singleton, but be careful: global state can be evil.
Not as bad as a singleton, you could use static fields/methods: it can be useful is some situations but should not be abused.
In any other situations (= most of the time), just use normal instance variables/methods.
You can use an enum to define a singleton.
public enum Foo {
INSTANCE;
int num1;
int num2;
public void func() {
// Something in here
}
}
public static void main(String[] args) {
Foo bar = Foo.INSTANCE;
}
However, this is only need if you want to enforce one instance. Otherwise, I would just use new Foo(); and call it only once, if you only need one.
You can use Singleton. However, make sure if Singleton is what is really required - sometimes singletons gets overused where simple class with static methods might suffice. There are many ways to create singleton as explained What is an efficient way to implement a singleton pattern in Java?
Note that with Java 5, enum is the preferred way to create singleton.
You say that i don't need more than that so my answer is that not make more than one and if you really like to enforce the instance that it should be only one for class then use the enum best way to implement the singleton in java
for example in datasource one really needs singleton
public enum UserActivity {
INSTANCE;
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
private UserActivity() {
this.dataSource = MysqlDb.getInstance().getDataSource();
this.jdbcTemplate = new JdbcTemplate(this.dataSource);
}
public void dostuff() {
...
}
}
and if you really need that then use it otherwise go with your current logic
A class that must be instantiated once and only once, is called a singleton. That knowledge should help you narrow down your search for information. To give you a head start:
Difference between static class and singleton pattern?
Why use a singleton instead of static methods?
Basically static methods and fields means that you don't need any instances of the class.
In you case you need 'singleton' class, you can either use enum or make it a singleton by yourself, using the specific set of rules.
It really depends on the scope of your application. If you want this object to be used as a singleton you would provide a static method to get the one and only instance of the class.
public class Foo
{
private static Foo instance ....
private Foo()
{
.....
}
public static Foo getInstance()
{
return instance;
}
}
If you plan to use a framework like spring you would just add one object to the application context.
<bean class="....Foo" id="fooInstance" scope="singleton">
....
</bean>
But maybe, you can refractor this class to hold only static methods. Then you can mark the class as final and provide a private constructor.
public final class Utils
{
private Utils(){}
public static .... doFoo(....)
{
....
}
}
Related
I am developing a design pattern, and I want to make sure that here is just one instance of a class in Java Virtual Machine, to funnel all requests for some resource through a single point, but I don't know if it is possible.
I can only think of a way to count instances of a class and destroy all instance after first is created.
Is this a right approach? If not, is there any other way?
Use the singleton pattern. The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().
The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance() method (which must be public) then simply returns this instance,
public class Singleton {
private static Singleton instance;
/**
* A private Constructor prevents any other class from
* instantiating.
*/
private Singleton() {
// nothing to do this time
}
/**
* The Static initializer constructs the instance at class
* loading time; this is to simulate a more involved
* construction process (it it were really simple, you'd just
* use an initializer)
*/
static {
instance = new Singleton();
}
/** Static 'instance' method */
public static Singleton getInstance() {
return instance;
}
// other methods protected by singleton-ness would be here...
/** A simple demo method */
public String demoMethod() {
return "demo";
}
}
Note that the method of using “lazy evaluation” in the getInstance() method (which
is advocated in Design Patterns), is not necessary in Java because Java already uses “lazy
loading.” Your singleton class will probably not get loaded unless its getInstance()
is called, so there is no point in trying to defer the singleton construction until it’s needed
by having getInstance() test the singleton variable for null and creating the singleton
there.
Using this class is equally simple: simply get and retain the reference, and invoke methods on it:
public class SingletonDemo {
public static void main(String[] args) {
Singleton tmp = Singleton.getInstance();
tmp.demoMethod();
}
}
Some commentators believe that a singleton should also provide a public final
clone() method that just throws an exception, to avoid subclasses that “cheat” and
clone() the singleton. However, it is clear that a class with only a private constructor
cannot be subclassed, so this paranoia does not appear to be necessary.
That's the well known Singleton pattern: you can implement this as follows:
public class SingletonClass {
//this field contains the single instance every initialized.
private static final instance = new SingletonClass();
//constructor *must* be private, otherwise other classes can make an instance as well
private SingletonClass () {
//initialize
}
//this is the method to obtain the single instance
public static SingletonClass getInstance () {
return instance;
}
}
You then call for the instance (like you would constructing a non-singleton) with:
SingletonClass.getInstance();
But in literature, a Singleton is in general considered to be a bad design idea. Of course this always somewhat depends on the situation, but most programmers advice against it. Only saying it, don't shoot on the messenger...
There is a school of thought that considers the Singleton pattern to in fact be an anti-pattern.
Considering a class A that you only wish to have one of, then an alternative is to have a builder or factory class that itself limits the creation of the number of objects of Class A, and that could be by a simple counter.
The advantage is that Class A no longer needs to worry about that, it concentrates on its real purpose. Every class that uses it no longer has to worry about it being a singleton either (no more getInstance() calls).
You want the Singleton pattern. There is an excellent discussion of how to implement this properly. If you do this right, there will only ever be one instance of the class.
Essentially what you are going to do is create a class, hold a single instantiated object of that class at the static level, and provide a static accessor to get it (getInstance() or similar). Make the constructor final so people can't create their own instances out of the blue. That link above has plenty of great advice on how to do this.
Use enum. In Java enum is the only true way to create a singleton. Private constructors can be still called through reflection.
See this StackOverflow question for more details:
Implementing Singleton with an Enum (in Java)
Discussion:
http://javarevisited.blogspot.com/2012/07/why-enum-singleton-are-better-in-java.html
I can only think of a way to count instances of a class and destroy all instance after first is created. Is this a right approach ? If not, is there any other way ?
The correct technical approach is to declare all of the constructors for the class as private so that instances of the class can only be created by the class itself. Then you code the class only ever create one instance.
Other Answers show some of the ways to implement this, according to the "Singleton" design pattern. However, implementing a singleton like this has some drawbacks, including making it significantly harder to write unit tests.
I prefer lazy singleton class, which overrides readResolve method.
For Serializable and Externalizable classes, the readResolve method allows a class to replace/resolve the object read from the stream before it is returned to the caller. By implementing the readResolve method, a class can directly control the types and instances of its own instances being deserialized.
Lazy singleton using /Initialization-on-demand_holder_idiom:
public final class LazySingleton {
private LazySingleton() {}
public static LazySingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazySingleton INSTANCE = new LazySingleton();
}
private Object readResolve() {
return LazyHolder.INSTANCE;
}
}
Key notes:
final keyword prohibits extension of this class by sub-classing
private constructor prohibits direct object creation with new operator in caller classes
readResolve prohibits creation of multiple instances of class during object de-serialization
For that you need to use singleton pattern, I am just posting a demo code for that that may useful for your understanding.
E.g: If I want only one object for this Connect class:
public final class Connect {
private Connect() {}
private volatile static Connect connect = null;
public static Connect getinstance() {
if(connect == null) {
synchronized (Connect.class) {
connect = new Connect();
}
}
return connect;
}
}
Here the constructor is private, so no one can use new keyword to make a new instance.
class A{
private A(){
}
public static A creator(A obj){
A ob=new A();
return ob;
}
void test(){
System.out.println("The method is called");
}
}
class Demo{
public static void main(String[] args){
A ob=null;
ob=A.creator(ob);
ob.test();
}
}
What is the purpose of getInstance() in Java?
During my research I keep reading that getInstance() helps achieve a Singleton design pattern (which means just one instance across the whole program to my understanding). But can't I just use static? Isn't that the whole point of static?
If I were to just have static methods and fields, how would it differ from using getInstance()? Is there a "scope" of static? For example, one instance per method or class?
And if they are different, in what cases would I choose getInstance() over using static?
I apologize if the question is unclear, I am sure I am missing something on the subject matter, I just can't figure out what.
Thank you for any and all advice.
Static will not give you a singleton. Since there is no way of making a top-level class a singleton in Java, you have getInstance methods which will implement some logic to to be sure there is only one instance of a class.
public class Singleton {
private static Singleton singleton;
private Singleton(){ }
public static synchronized Singleton getInstance( ) {
if (singleton == null)
singleton=new Singleton();
return singleton;
}
}
Check out this top answer: Static Classes In Java
The above code will allow only one instance to be created, and it's clean, however as of Java 1.6, it is better to create singleton's as such since it is slightly more elegant IMHO:
public enum MyEnumSingleton {
INSTANCE;
// other useful methods here
}
Source: http://www.vogella.com/tutorials/DesignPatternSingleton/article.html
Singleton
A singleton allows you to use a single reference to a java Object. For example, here is a singleton which contains a number;
public class MySingleton {
private int myNumber;
private static MySingleton instance;
public static MySingleton getInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}
private MySingleton() {}
public void setMyNumber(int myNumber) {
this.myNumber = myNumber;
}
public int getMyNumber() {
return myNumber;
}
}
Now we are going to set the value of this number in the A class:
public class A {
/*...*/
MySingleton mySingleton = MySingleton.getInstance();
mySingleton.setMyNumber(42);
/*...*/
}
Then, you can access this value from another class:
public class B {
/*...*/
MySingleton mySingleton = MySingleton.getInstance();
int number = mySingleton.getMyNumber();
/*...*/
}
In this class the number variable will have the value 42. This is the advantage of a singleton over a simple object:
All the values stored in the singleton will be accessible from
"everywhere".
Static class
The purpose is different, here the advantage is to use an object without having to create it.
For example:
public static class MyStaticClass {
public static void sayHello() {
System.out.println("Hello");
}
}
Now you can use the sayHello() method from any classes by calling:
MyStaticClass.sayHello();
The exact method of implementing a singleton, for example using a factory method called getInstance(), isn't that relevant to the question, which is "static methods vs singleton with instance methods".
Classes are themselves effectively singletons, so from that aspect they are similar.
The main difference is that static methods are not part of class hierarchy - they are not inherited, which means the static method option locks you forever to using that exact class and it can't be referred to in any other way, such being an implementation of some interface or a super class.
Instances however don't have this problem, so you can code for example:
class MySingleton implements SomeInterface {
...
}
SomeInterface instance = MySingleton.getInstance();
I prefer to use static too, but sometimes getInstance() is helpful to have some functions that will be related to the object, in which you can modify variables. if you are simply making some util functions that do not need an instance of an object, use static.
When you are using someone's libraries, you never know if a function body needs a class instance. That's why a lot of library classes are using getInstance().
Instead of checking for null, I like this a little better.
public class SingleObject {
//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
//instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject getInstance(){
return instance;
}
}
Called with...
public class SingletonPatternDemo {
public static void main(String[] args) {
//illegal construct
//Compile Time Error: The constructor SingleObject() is not visible
//SingleObject object = new SingleObject();
//Get the only object available
SingleObject object = SingleObject.getInstance();
}
}
Full code from: http://www.tutorialspoint.com/design_pattern/singleton_pattern.htm
One overlooked reason to use a singleton instead of static class member variables is that the static member variables MAY use space and garbage collector time even in the event the class is never instantiated. Consider how many classes are available to you in rt.jar and what a small fraction of them you probably use in any given application. Also consider that using getInstance ensures your "constructor" has run before any of the member variables are accessed. I almost universally see getInstance as synchronized but I feel this is a bad idea. If anyone ever adds a synchronized blocking method calls to Singleton.getInstance().unsynchronized() could be needlessly held up.
private static Singleton instance = null;
private Singleton() {}
public final static Singleton getInstance() {
return (instance != null) ? instance : makeInstance();
}
private final static synchronized Singleton makeInstance() {
return ( instance != null ) ? instance : ( instance = new Singleton() );
}
In Java we can do the following to initialize class and call method inside that class:
public class MyClass {
public String myClassMethod() {
return "MyClass";
}
}
.
public class Test {
public static void main(String[] args) {
MyClass myClass = new MyClass(); // initialize MyClass
myClass.myClassMethod();// call a method
}
}
If my class is an enum class, implementation will be the following:
public enum MyEnumClass {
INSTANCE;
public String myEnumClassMethod() {
return "MyEnumClass";
}
}
.
public class Test {
public static void main(String[] args) {
MyEnumClass myEnumClass = MyEnumClass.INSTANCE;
myEnumClass.myEnumClassMethod();
}
}
Both of these cases works in the same way, but it is said to be better in the enum implementation. My question is why and how it is happening?
An enum is essentially a singleton pattern.
The JVM handles the initialization and storage of enum instances. To see this most clearly you can write:
public enum MyEnumClass {
INSTANCE("some value for the string.");
private final String someString;
private MyEnumClass(final String someString) {
this.someString = someString;
}
public String getSomeString(){
return someString;
}
}
And in another class:
public static void main(String[] args) {
final MyEnumClass myEnumClass = MyEnumClass.INSTANCE;
system.out.println(myEnumClass.getSomeString());
}
This would print out "some value for the string.".
This demonstrates that the enum instances are initialised at class load time, i.e. as if by the static initialiser.
Or put another way:
new MyClass() == new MyClass();
Is always false, whereas:
MyEnumClass.INSTANCE == MyEnumClass.INSTANCE;
Is always true. i.e. MyEnumClass.INSTANCE is always the same MyEnumClass.INSTANCE whereas a new MyClass is created every time your call new MyClass().
This brings us nicely to your question of "better".
An enum is a singleton instance with various nifty methods for converting String enum names into a reference to the singleton instance that it represents. It also guarantees that if you de-serialize an enum there won't be two separate instances like there would for a normal class.
So an enum is certainly much better as a robust and threadsafe singleton than a class.
But we cannot have two instances of INSTANCE with the different values for someString so the enum is useless as a class...
In short enums are good for what they're good for and classes are good for what they're good for. They are not substitutes and therefore cannot be compared in any meaningful way expect when one is used as the other.
It's a simple implementation of the Singleton pattern, relying on the mechanisms of how Enum's work.
If you use MyEnumClass.INSTANCE a second time, you'll get the same object instance.
In contrast, new MyClass(); will create a new object.
See also discussion here:
What is the best approach for using an Enum as a singleton in Java?
There would possibly be more to learn by reading Java Language Spec Section 8-9
Here is the question:
Implement a singleton design pattern as a template such that, for any given class
Foo, you can call Singleton::instance() and get a pointer to an instance of a singleton
of type Foo. Assume the existence of a class Lock which has acquire() and release()
methods. How could you make your implementation thread safe and exception safe?
My analysis:
as Joshua Bloch points out in "effective java", the better ways to implement
a singleton class is enum and public static factory method. Combining volatile
and synchronized is the way I know to make it thread safe and lazy initialization
as follows
public class myS{
private static volatile final _ins = null;
private myS(){};
public static myS getIns(){
synchronized(){
if(_ins==null) _ins = new myS();
}
return _ins;
}
}
At this moment, I am a little confused to make a singleton template. My understanding is that we either have an interface with generic type or an abstract class. As long as the clients implement them, they are singleton. So, my guess solution is as follows:
public interface singleton<T>{
public T instance();
}
public class Foo implements singleton<T>{
private static volatile final Foo _ins = null;
public static Foo instance(){
synchronized(this)
if(_ins==null){
_ins = new Foo();
}
}
}
}
The easiest way to get singleton functionality is to use a Dependancy Injection (DI) framework like Spring. There are plenty of other benefits gained by using DI as well.
'singleton' does not fit with 'template'. It is a kind of contradiction. If think you will be better off implementing enums as following
public enum MySingleton1 {
;
public static void MethodA() { ... };
}
public enum MySingleton2 {
;
public static int MethodB() { ... };
}
EDIT
A solution without enums would be:
public interface singletonMarker{};
public final class MySingleton1() extends singletonMarker {
public static final MySingleton1 INSTANCE = new MySingleton1();
private MySingleton1() {};
public synchronized int mySyncMethod() { ... };
}
Usage
MySingleton1.INSTANCE.mySyncMethod();
The interface is only acting as marker, but it is not really necessary.
How do you define Global variables in Java ?
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;
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.
Another way is to create an interface like this:
public interface GlobalConstants
{
String name = "Chilly Billy";
String address = "10 Chicken head Lane";
}
Any class that needs to use them only has to implement the interface:
public class GlobalImpl implements GlobalConstants
{
public GlobalImpl()
{
System.out.println(name);
}
}
You are better off using dependency injection:
public class Globals {
public int a;
public int b;
}
public class UsesGlobals {
private final Globals globals;
public UsesGlobals(Globals globals) {
this.globals = globals;
}
}
Lots of good answers, but I want to give this example as it's considered the more proper way to access variables of a class by another class: using getters and setters.
The reason why you use getters and setters this way instead of just making the variable public is as follows. Lets say your var is going to be a global parameter that you NEVER want someone to change during the execution of your program (in the case when you are developing code with a team), something like maybe the URL for a website. In theory this could change and may be used many times in your program, so you want to use a global var to be able to update it all at once. But you do not want someone else to go in and change this var (possibly without realizing how important it is). In that case you simply do not include a setter method, and only include the getter method.
public class Global{
private static int var = 5;
public static int getVar(){
return Global.var;
}
//If you do not want to change the var ever then do not include this
public static void setVar(int var){
Global.var = var;
}
}
Truly speaking there is not a concept of "GLOBAL" in a java OO program
Nevertheless there is some truth behind your question because there will be some cases where you want to run a method at any part of the program.
For example---random() method in Phrase-O-Matic app;it is a method should be callable from anywhere of a program.
So in order to satisfy the things like Above "We need to have Global-like variables and methods"
TO DECLARE A VARIABLE AS GLOBAL.
1.Mark the variable as public static final While declaring.
TO DECLARE A METHOD AS GLOBAL.
1. Mark the method as public static While declaring.
Because I declared global variables and method as static you can call them anywhere you wish by simply with the help of following code
ClassName.X
NOTE: X can be either method name or variable name as per the requirement and ClassName is the name of the class in which you declared them.
There is no global variable in Java
Nevertheless, what we do have is a static keyword and that is all we need.
Nothing exists outside of class in Java. The static keyword represents a class variable that, contrary to instance variable, only has one copy and that transcends across all the instances of that class created, which means that its value can be changed and accessed across all instances at any point.
If you need a global variable which can be accessed beyond scopes, then this is the variable that you need, but its scope exists only where the class is, and that will be all.
Nothing should be global, except for constants.
public class MyMainClass {
public final static boolean DEBUGMODE=true;
}
Put this within your main class. In other .java files, use it through:
if(MyMainClass.DEBUGMODE) System.out.println("Some debugging info");
Make sure when you move your code off the cutting room floor and into release you remove or comment out this functionality.
If you have a workhorse method, like a randomizer, I suggest creating a "Toolbox" package! All coders should have one, then whenever you want to use it in a .java, just import it!
There is no such thing as a truly global variable in Java. Every static variable must belong to some class (like System.out), but when you have decided which class it will go in, you can refer to it from everywhere loaded by the same classloader.
Note that static variables should always be protected when updating to avoid race conditions.
Understanding the problem
I consider the qualification of global variable as a variable that could be accessed and changed anywhere in the code without caring about static/instance call or passing any reference from one class to another.
Usually if you have class A
public class A {
private int myVar;
public A(int myVar) {
this.myVar = myVar;
}
public int getMyVar() {
return myVar;
}
public void setMyVar(int mewVar) {
this.myVar = newVar;
}
}
and want to access and update myvar in a class B,
public class B{
private A a;
public void passA(A a){
this.a = a;
}
public void changeMyVar(int newVar){
a.setMyvar(newVar);
}
}
you will need to have a reference of an instance of the class A and update the value in the class B like this:
int initialValue = 2;
int newValue = 3;
A a = new A(initialValue);
B b = new B();
b.passA(a);
b.changeMyVar(newValue);
assertEquals(a.getMyVar(),newValue); // true
Solution
So my solution to this, (even if i'm not sure if it's a good practice), is to use a singleton:
public class Globals {
private static Globals globalsInstance = new Globals();
public static Globals getInstance() {
return globalsInstance;
}
private int myVar = 2;
private Globals() {
}
public int getMyVar() {
return myVar;
}
public void setMyVar(int myVar) {
this.myVar = myVar;
}
}
Now you can get the Global unique instance anywhere with:
Globals globals = Globals.getInstance();
// and read and write to myVar with the getter and setter like
int myVar = globals.getMyVar();
global.setMyVar(3);
public class GlobalClass {
public static int x = 37;
public static String s = "aaa";
}
This way you can access them with GlobalClass.x and GlobalClass.s
If you need to update global property, a simple getter/setter wrapper class can be used as global variable. A typical example is shown below.
public class GlobalHolder {
private static final GlobalHolder INSTANCE = new GlobalHolder();
private volatile int globalProperty;
public static GlobalHolder getInstance() {
return INSTANCE;
}
public int getGlobalProperty() {
return globalProperty;
}
public void setGlobalProperty(int globalProperty) {
this.globalProperty = globalProperty;
}
public static void main(String[] args) {
GlobalHolder.getInstance().setGlobalProperty(10);
System.out.println(GlobalHolder.getInstance().getGlobalProperty());
}
}
public class GlobalImpl {
public static int global = 5;
}
you can call anywhere you want:
GlobalImpl.global // 5
Creating an independent file, eg. Example.java to use the 1st solution, is just fine. You can do that also within the app, if e.g. the global variables are special to your current app, etc.:
Create a class at the beginning and declare your variables in there:
class Globals {
static int month_number;
static String month_name;
}
You can then access these variables -- using them as 'Globals.month_number', etc. -- from averywhere in your app.
very simple:
class UseOfGlobal
{
private static int a;
private static int b;
}
but it is always good to have local variables defined inside method blocks where ever possible.
As you probably guess from the answer there is no global variables in Java and the only thing you can do is to create a class with static members:
public class Global {
public static int a;
}
You can use it with Global.a elsewhere. However if you use Java 1.5 or better you can use the import static magic to make it look even more as a real global variable:
import static test.Global.*;
public class UseGlobal {
public void foo() {
int i = a;
}
}
And voilà!
Now this is far from a best practice so as you can see in the commercials: don't do this at home
There are no global variables in Java, but there are global classes with public fields. You can use static import feature of java 5 to make it look almost like global variables.
Generally Global variable (I assume you are comparing it with C,Cpp) define as public static final
like
class GlobalConstant{
public static final String CODE = "cd";
}
ENUMs are also useful in such scenario :
For Example Calendar.JANUARY)
To allow an unqualified access to static members of another class, you can also do a static import:
import static my.package.GlobalConstants;
Now, instead of print(GlobalConstants.MY_PASSWORD);
you can use the Constant directly: print(MY_PASSWORD);
See What does the "static" modifier after "import" mean? to decide about.
And consider the answer of Evan Lévesque about interfaces to carry the Constants.
// Get the access of global while retaining priveleges.
// You can access variables in one class from another, with provisions.
// The primitive must be protected or no modifier (seen in example).
// the first class
public class farm{
int eggs; // an integer to be set by constructor
fox afox; // declaration of a fox object
// the constructor inits
farm(){
eggs = 4;
afox = new fox(); // an instance of a fox object
// show count of eggs before the fox arrives
System.out.println("Count of eggs before: " + eggs);
// call class fox, afox method, pass myFarm as a reference
afox.stealEgg(this);
// show the farm class, myFarm, primitive value
System.out.println("Count of eggs after : " + eggs);
} // end constructor
public static void main(String[] args){
// instance of a farm class object
farm myFarm = new farm();
}; // end main
} // end class
// the second class
public class fox{
// theFarm is the myFarm object instance
// any public, protected, or "no modifier" variable is accessible
void stealEgg(farm theFarm){ --theFarm.eggs; }
} // end class
Going by the concept, global variables, also known as instance variable are the class level variables,i.e., they are defined inside a class but outside methods. In order to make them available completely and use them directly provide the static keyword.
So if i am writing a program for simple arithmetical operation and it requires a number pair then two instance variables are defined as such:
public class Add {
static int a;
static int b;
static int c;
public static void main(String arg[]) {
c=sum();
System.out.println("Sum is: "+c);
}
static int sum() {
a=20;
b=30;
return a+b;
}
}
Output: Sum is: 50
Moreover using static keyword prior to the instance variables enable us not to specify datatypes for same variables again and again. Just write the variable directly.
In general, Java doesn't have any global variables. Other than local variables, all variables comes under the scope of any class defined in the program.
We can have static variables to have the scope of global variables.
without static this is possible too:
class Main {
String globalVar = "Global Value";
class Class1 {
Class1() {
System.out.println("Class1: "+globalVar);
globalVar += " - changed";
} }
class Class2 {
Class2() {
System.out.println("Class2: "+globalVar);
} }
public static void main(String[] args) {
Main m = new Main();
m.mainCode();
}
void mainCode() {
Class1 o1 = new Class1();
Class2 o2 = new Class2();
}
}
/*
Output:
Class1: Global Value
Class2: Global Value - changed
*/
Object-Oriented Programming is built with the understanding that the scope of variables is closely exclusive to the class object that encapsulates those variables.
The problem with creating "global variables" is that it's not industry standard for Java. It's not industry standard because it allows multiple classes to manipulate data asyncronized, if you're running a multi-threaded application, this gets a little more complicated and dangerous in terms of thread-safety. There are various other reasons why using global variables are ineffective, but if you want to avoid that, I suggest you resort to Aspect-Oriented Programming.
Aspect-Oriented Programming negates this problem by putting the parent class in charge of the scope through something called "advices", which adds additional behavior to the code without actually modifying it. It offers solutions to cross-cutting concerns, or global variable usage.
Spring is a Java framework that utilizes AOP, and while it is traditionally used for web-applications, the core application can be used universally throughout the Java framework (8.0 included). This might be a direction you want to explore more.
To define Global Variable you can make use of static Keyword
public final class Tools {
public static int a;
public static int b;
}
now you can access a and b from anywhere by calling
Tools.a;
Tools.b;
Yoy are right...specially in J2ME...
You can avoid NullPointerException by putting inside your MidLet constructor
(proggy initialization) this line of code:
new Tools();
This ensures that Tools will be allocated before any instruction
that uses it.
That's it!