0

A在类中有一个方法Test,它生成一个数字ab下面是它的代码:

public class Test
{
    int a,b;

    public void A()
    {
        a = currentMenu.getCurrentFocusedItem().getItemID();
        b = currentMenu.getMenuID();
        System.out.println("Inside A ()" + a  + " &&" + b);
    }

    public void B()
    {
        System.out.println("Inside B ()" + a  + " &&" + b);
    }
}

现在,我想在同一个 类文件中将ab int值访问到另一个方法中。需要一些指针 B()

4

4 回答 4

1

instance您可以在初始化中获取 a 和 b 值block

public class TestClass {
    int a,b;
    {
         a= 10;
         b =45;
    }

    public void A() {
        System.out.println("Inside A ()" + a + " &&" + b);
    }

    public void B() {
        System.out.println("Inside B ()" + a + " &&" + b);
    }

}

使用此方法,您不必调用您的A()方法来填充要使用的值B()

于 2013-08-12T08:44:43.110 回答
1

如果您正在使用该类的同一实例,则在 method 中设置的和Test的值应该仍然在 method 中可见。abA()B()

因此,以下将起作用:

Test test = new Test();

test.A();
test.B();

但是,下面不会

new Test().A();
new Test().B();

附带说明一下,Java 中的方法应始终以小写字母开头并使用驼峰式。

于 2013-08-12T08:45:01.810 回答
1

如果您要做的是获取 a 和 b 的当前(和最新)值,您可以编写 2 种方法,例如

public int getA() {
    return currentMenu.getCurrentFocusedItem().getItemID();
}

public int getB() {
    return currentMenu.getMenuID();
}

并使用这些方法而不是调用 A() 来更新 a、b 的值,然后在方法 B 中再次访问它们。

于 2013-08-12T08:51:54.193 回答
0

你也可以试试这个

  public void A()
{
    a = currentMenu.getCurrentFocusedItem().getItemID();
    b = currentMenu.getMenuID();
    System.out.println("Inside A ()" + a  + " &&" + b);
}
public void B()
{
    Test test=new Test();
    test.A();      // assign values for a and b
    System.out.println("Inside B ()" + a  + " &&" + b);
}
于 2013-08-12T08:54:02.273 回答