[英]Java: How to change values of instance variables with methods
我是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 static void main(String args[]){
System.out.print(y);
}
}
y
是静态变量,因此它属于类(但不属于类实例),因此可以从静态方法main
访问它。 x == 1
=> x > 0
因此y = Message A.
public static void main(String args[]){
setString();
System.out.print(y);
}
要使用方法更改实例变量的值,您需要使用“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());
}
}
您需要使用类本身访问静态变量的值。 下面的代码可能会给你一个想法。 函数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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.