怎样声明才能是stringbuilder字符串能在每个函数中都能引用?

来源:百度知道 编辑:UC知道 时间:2024/05/23 03:16:27
现在声明了一个sb stringBuilder字符串变量,怎样才能使它在fun1()中引用,又能在fun2()中引用呢?

声明为全局变量(外部变量),即变量写在函数外.
如:
//main类
public class Test
{
public static void main(String[] args)
{
Test2 te = new Test2();
te.chan();
te.chan2();
}
}
//Test2 类
public class Test2
{
public int a = 0;//定义为全局变量的a
public Test2()
{}

public void chan()
{
a++;
System.out.println("chan a=" + a);
}

public void chan2()
{
a++;
System.out.println("chan2 a=" + a);
}
}
上例中的chan() 和 chan2() 都能调用a变量;
但任何一个函数都可能修改其值,若要它始终不变,则定义为常量,即在变量类型前加fianl关键字如上例中的
public int a = 0;
改为:
public fianl int a = 0;

public static

你可以把它定义为类变量啊,
这样在类中的方法就都能使用了 .