public class DemoClass {
public void setValue(int a, int b)
{
int x=a;
int y=b;
}
public void getValue()
{
}
public static void main(String[] args)
{
DemoClass dc=new DemoClass();
dc.setValue(10, 20);
dc.getValue();
}
}
在上面的程序中,我有两个方法setValue()和getValue()。 SetValue方法有两个变量x和y,它们分配值10和20(来自main方法)。
现在我想在getValue()方法中显示x和y变量的值。但这不可能,因为它们是局部变量。有没有办法做到这一点?
答案 0 :(得分:3)
有没有办法做到这一点?
通常的做法是让他们成为班级的 fields ,特别是实例字段:
public class DemoClass {
private int x; // These are
private int y; // instance fields
public void setValue(int a, int b)
{
this.x = a;
this.y = b;
}
public void getValue()
{
// Use `this.x` and `this.y` here
}
public static void main(String[] args)
{
DemoClass dc=new DemoClass();
dc.setValue(10, 20);
dc.getValue();
}
}
使用单个setValue
方法设置两个单独的字段相对较少,但有一些用例。通常,您有setX
和setY
(以及getX
和getY
)。
答案 1 :(得分:0)
您可以将它们设置为公开,或者如果您想使用getter和setter,则可以执行此操作。
public class DemoClass {
private int x;
private int y;
public void setValue(int a, int b)
{
this.x=a;
this.y=b;
}
public void getValue()
{
System.out.println(this.x);
System.out.println(this.y);
}
public static void main(String[] args)
{
DemoClass dc=new DemoClass();
tc.setValue(10, 20);
tc.getValue();
}
}
您还可以将信息放在构造函数中,如下所示:
public class DemoClass {
private int x;
private int y;
public DemoClass() {
this.x = 0; // default value
this.y = 0; // default value
}
public void setValue(int a, int b)
{
this.x=a;
this.y=b;
}
public void getValue()
{
System.out.println(this.x);
System.out.println(this.y);
}
public static void main(String[] args)
{
DemoClass dc=new DemoClass();
tc.setValue(10, 20);
tc.getValue();
}
}
这样,当您创建对象时:
DemoClass demoClass = new DemoClass();
它已经设置了这些对象。如果您不这样做并且不小心调用了getValue()并且没有设置任何内容,那么您将获得nullPointerException
。