有两个类其中一个类想得到另一个类中的一个变量应该怎么写?
如:
class a{
public static void one()
{
int i = 1;
}
}
class b{
public static void second()
{
在这里怎么才能得到a类中i的值
}
}

解决方案 »

  1.   

    i 是 one()的局部变量
    作用域仅在{}中
      

  2.   

    public class AAA{
       private int i=0;
       public static void one(){
           i = 1;
       }
    }public class BBB{
        AAA a = new AAA();
        a.i;//这个就可以得到
        AAA.i;//或者这个
    }
      

  3.   

    public static void one()
    {
    int i = 1;
    }
    这里的i是局部变量函数结束就没有了,用一个成员变量存储值,楼上的代码中有一点问题
    public class AAA{
       private int i=0;  //->这里改为public int i=0;
       public static void one(){
           i = 1;
       }
    }public class BBB{
        AAA a = new AAA();
        a.i;//这个就可以得到
        AAA.i;//或者这个
    }
      

  4.   

    public static void one()
    {
    int i = 1;
    }
    i是局部变量,作用域在one()中,无法被外界访问。只有成员变量才能被外界访问。public class A{
       private int i=0;  //->这里改为public int i=0;
    }public class B{
        A a = new A();
        a.i;//可以得到
        A.i;//或者这样
    }
      

  5.   

    class a{
    public static void one()
    {
    int i = 1;
    }
    }
    class b{
    public static void second()
    {
    在这里怎么才能得到a类中i的值
    }
    }
    -------------------------------------------------
    在这里,i为方法内局部变量,出了含有它的方法,它就无效了不能再使用。
    如果你想要在与这个类没有任何关系的类中调用这个类的成员变量,这个变量要么是public的要么你就要为它提供get()、set()方法由于你的方法是静态的,所以你在定义这个类的成员变量时也必须是静态的,因为静态方法只能调用静态的成员变量。class A{
    public static int i;
    public static void one()
    {
    i = 1;
    }
    }
    class B{
    public static void second()
    {
    //A.i 就可以调用到你想要的值了
    }
    }
      

  6.   

    也可以写成这样
    class A{
    public static int i;
    public static int one()
    {
    return (i = 1);
    }
    }
    class B{
    public static void second()
    {
    //A.one() 就可以调用到你想要的值了
    }
    }
      

  7.   

    不好意思,上面的写错了
    应该写成这样,利用返回值传递数值class A{
    public static int one()
    {
    int i;
    return (i = 1);
    }
    }
    class B{
    public static void second()
    {
    //A.one() 就可以调用到你想要的值了
    }
    }