In this code, I am trying to make global instance of class so any methods can use it:
public static void clip(){
while(!Display.isCloseRequested()){
glClear(GL_COLOR_BUFFER_BIT);
if(character.gravity)character.y++; //there is an error, it says "Variable character does not exist"
Display.update();
Display.sync(70);
}
}
public static void initGame(){
entity character = new entity(); // I want to use this in method clip()
character.create(true, "box", true);
}
I've searched google, but on my question "Make instances of class global" found nothing. Thanks for help.
If you want one global object for a class, you can make a Singleton as follows.
Now you can access the "global" instance:
In Java, all objects should either be variables or members of a class, even though they are static members. C-style globals do not exist.
So in your case, to make the
character
accessible from everywhere, you should write:And, provided the code above is from the class
MyClass
, and the code below from another class:This being said, this code (its design actually) should be improved as it is absolutely not object oriented. As this is another question I won't elaborate further here but suggest that you investigate further in OOP standards and best practices.
There is no such thing as a "global variable" in java.
However, you can declare
character
as a class variable by declaring:outside of methods, only on the class scope.
Something like that:
More info on class variables can be in the official documentation.
As a side node, a class should not be named
entity
, since java has a strong convention that classes names should always start with upper case letter, you should rename this class toEntity
.Create singleton instance of your global class, and add static instance getter for it. Later on in any piece of your code you will be able to get your instance and call any public method of its class. Alternativly if you dont need singletons, simply use static method.
To make an instance of a particular class global to your program, one solution is the Singleton pattern. It works in the following way:
You can then use the unique instance of class Entity from wherever in the code by: