Re: Re: Java Variable Help?

Front Page Forums MCNSA Java Variable Help? Re: Re: Java Variable Help?

#3108
Kenix
Member

I 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 ---