This site requires JavaScript, please enable it in your browser!
Greenfoot back
Jemy2
Jemy2 wrote ...

2021/5/5

How to reference a variable define in world to other class

Jemy2 Jemy2

2021/5/5

#
private static int NUMBER_OF_SERVER = 31;
The variable NUMBER_OF_SERVER, how can i use it in another class
Super_Hippo Super_Hippo

2021/5/5

#
It is private and static. Private means that you can’t directly access if from outside the class. Static means that it is a variable for the class and there is not an individual variable for each object of the class. The name of the variable suggests that it would be a final variable which is only defined once and never changed, but it doesn’t have the keyword. To access the variable from somewhere else in its current form, you need a public method in the same class – often called a “getter”-method.
public static int getNumServer() {return NUMBER_OF_SERVER;}
You can then call that method from anywhere to get the value of it.
int x = MyWorld.getNumServer(); //with MyWorld being the class name of the class in which the method is
Jemy2 Jemy2

2021/5/5

#
Super_Hippo wrote...
It is private and static. Private means that you can’t directly access if from outside the class. Static means that it is a variable for the class and there is not an individual variable for each object of the class. The name of the variable suggests that it would be a final variable which is only defined once and never changed, but it doesn’t have the keyword. To access the variable from somewhere else in its current form, you need a public method in the same class – often called a “getter”-method.
public static int getNumServer() {return NUMBER_OF_SERVER;}
You can then call that method from anywhere to get the value of it.
int x = MyWorld.getNumServer(); //with MyWorld being the class name of the class in which the method is
Thank you
You need to login to post a reply.