Front Page › Forums › MCNSA › Java Variable Help?
- This topic is empty.
-
AuthorPosts
-
April 26, 2012 at 4:27 am #249
quantumkitty
ParticipantSo, i’m rather confused. i know how to initialize variables and, for the most part, use them.
The problem for me, however, is when I attempt to use said variables in a different class in the project. For example, I would have a variable called “Health” in one class. An event in an outside class, like the use of specific potion would increase the health, but I do not know how to change variables through classes.I’ve tried to fix it through experimentation, such as using “public int Health = 0;” but, as i’ve long ago realized… It don’t do shit.
Anyone willing to give me a short tutorial on using one variable in multiple classes?
even the java bible hasn’t helped me one bit D:April 26, 2012 at 4:38 am #3106quantumkitty
Participantoh, right, and as i do remember the rules:
boolean kickedmicro = false;
while(kickedmicro == false)
{
System.out.println("quick, kick micro!");
if (kickedmicro == false)
{
Kick("Microsoftt");
kickedmicro = true;
}
else
{
System.out.println("how are you even in this loop then? o.o");
}
}
April 26, 2012 at 4:39 am #3107quantumkitty
Participantignore mah choppy and completely wrong coding 😀
April 26, 2012 at 7:49 am #3108Kenix
MemberI think what you are looking for is either making it public or encapsulate it with setter and getter methods. Using encapsulation is recommended but both methods will work.
Try read section 5.1.3 of this article
Made an example for you to get the idea,
public class MyClass {
private int privateHealth = 0;
public int publicHealth = 0;
// Sets the value private health
public void setPrivateHealth( int newHealth ) {
privateHealth = newHealth ;
}
// Gets the private health value
public int getPrivateHealth () {
return privateHealth ;
}
public static void main(String[] args) {
// Initialize new instance of myClass
MyClass myClass = new MyClass();
//Test the private health setters and getters
System.out.println(myClass.getPrivateHealth ());
myClass.setPrivateHealth(5);
System.out.println(myClass.getPrivateHealth ());
//Test the public health
System.out.println(myClass.publicHealth);
myClass.publicHealth = 3;
System.out.println(myClass.publicHealth);
}
}
// --- Starting Execution ---
// 0
// 5
// 0
// 3
// --- Finished Execution Normally ---April 26, 2012 at 7:56 pm #3109quantumkitty
ParticipantAh, thank you very much XD
i think i could understand it with just the example you gave, but the article should help a lot 😀 -
AuthorPosts
- You must be logged in to reply to this topic.