有两个类其中一个类想得到另一个类中的一个变量应该怎么写?
如:
class a{
public static void one()
{
int i = 1;
}
}
class b{
public static void second()
{
在这里怎么才能得到a类中i的值
}
}
如:
class a{
public static void one()
{
int i = 1;
}
}
class b{
public static void second()
{
在这里怎么才能得到a类中i的值
}
}
作用域仅在{}中
private int i=0;
public static void one(){
i = 1;
}
}public class BBB{
AAA a = new AAA();
a.i;//这个就可以得到
AAA.i;//或者这个
}
{
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;//或者这个
}
{
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;//或者这样
}
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 就可以调用到你想要的值了
}
}
class A{
public static int i;
public static int one()
{
return (i = 1);
}
}
class B{
public static void second()
{
//A.one() 就可以调用到你想要的值了
}
}
应该写成这样,利用返回值传递数值class A{
public static int one()
{
int i;
return (i = 1);
}
}
class B{
public static void second()
{
//A.one() 就可以调用到你想要的值了
}
}