Java:如何使用方法更改实例变量的值
我对Java完全陌生,如果我能得到一个链接到另一个可能已经涉及这个新问题的线程,我将不胜感激 但是如何使用方法更改实例变量的值呢Java:如何使用方法更改实例变量的值,java,oop,static,Java,Oop,Static,我对Java完全陌生,如果我能得到一个链接到另一个可能已经涉及这个新问题的线程,我将不胜感激 但是如何使用方法更改实例变量的值呢 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 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);
}
}
y
是静态变量,因此它属于类(但不属于类实例),因此可以从静态方法main
访问它。
x==1
=>x>0
因此y=消息A.
public static void main(String args[]){
setString();
System.out.print(y);
}
您需要使用类本身访问静态变量的值。下面的代码可能会给你一个想法。函数print是由实例化对象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();
}
}
要更改实例变量的值,需要使用 实例方法和更改实例状态的方法 实例称为“setter”或mutator。例如:
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);
}
}
要使用方法更改实例变量的值,需要使用“setter”和“getter”方法。 示例:
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());
}
}