Reputation: 56
I am completely new to Java and I much appreciate it if I could get a link to another thread that probably already covered this newb question.
But how do you change the value of an instance variable with a method?
public class Example{
private static int x = 1;
private static String y;
public static void setString(){
if (x > 0){y = "Message A.";}
else{y = "Message B.";}
}
public static void main(String args[]){
System.out.print(y);
}
}
Upvotes: 2
Views: 20135
Reputation: 11
To change the value of instance variable using method you need to use "setter" and "getter" method. Example :
public class ABC
{
private String name; // instance variable
// method to set the name in the object
public void setName(String name)
{
this.name = name; // store the name
}
// method to retrieve the name from the object
public String getName()
{
return name;
}
public static void main(String args[]){
ABC b = new ABC();
Scanner input = new Scanner(System.in);
String name = input.nextLine(); // read a line of text
b.setName(name); // put name in ABC
System.out.println("NAME IS "+ b.getName());
}
}
Upvotes: 1
Reputation: 1
To change the value of an instance variable, you need to use an instance method and such a method which changes the state of an instance is called a 'setter' or mutator. For example:
public class Example {
private static int x = 1;
private int a; // Instance variable
private static String y;
public static void setString(){
if (x > 0){y = "Message A.";}
else{y = "Message B.";}
}
public void setA(int a) { // This is a mutator
this.a = a; // Sets the value of a to the specified 'a'
}
public void getA() { // This is an accessor
return a; // we return a
}
public static void main(String args[]){
Example k = new Example();
k.setA(4);
System.out.println(k.a);
}
}
Upvotes: 0
Reputation: 307
You need to access value of static variable using the class itself. Below code might gives you an idea. Function print is a non static function that is called by a instantiated object e.
public class Example{
private static int x = 1;
private static String y;
public static void setString(){
if (x > 0){y = "Message A.";}
else{y = "Message B.";}
}
public void print(){
System.out.println("x "+x);
System.out.println("y "+y);
}
public static void main(String args[]){
System.out.print(y);
Example.x = 0;
Example e = new Example();
Example.setString();
e.print();
}
}
Upvotes: 0
Reputation: 18255
y
is static variable, therefore it belongs to class (but not to class instance), therefore it is accessible from static method main
.
x == 1
=> x > 0
therefore y = Message A.
public static void main(String args[]){
setString();
System.out.print(y);
}
Upvotes: 2