java的那些个变量
1、instant var /实例变量 /
public
1、实例变量在一个类里面直接声明 public int x;
2、在另一个类中创建一个实例 th1\th2
3、在另一个类中饮用实例变量 th1.x\th2.x
import acm.program.*;
public class instance_var_public extends ConsoleProgram{
public void run() {
Thing th1=new Thing();
Thing th2=new Thing();
th1.x=8;
th2.x=17;
println(th1.x);
println(th2.x);
}
}
class Thing{
public Thing() {
x=0;
}
public int x;
}
private
1、实例变量在第一个类里面直接声明 private int x
2、在第一个类里面创建一个方法可以让另一个类访问到x 【public int getx(int x) 】
2、在另一个类中创建一个实例 th1\th2
3、在另一个类中饮用实例变量 th1.getx()\th2.getx()
import acm.program.*;
public class instance_var_public extends ConsoleProgram{
public void run() {
Thing th1=new Thing();
Thing th2=new Thing();
th1.getx(8);
th2.getx(17);
println(th1.getx(8));
println(th2.getx(17));
}
}
class Thing{
public Thing() {
x=0;
}
public int getx(int y) {
x=y;
return x;
}
private int x;
}
2、class var
public
和实例变量的区别在于类变量作用于全类,这里statics x的值都是10
import acm.program.*;
public class instance_var_public extends ConsoleProgram{
public void run() {
Thing th1=new Thing();
Thing th2=new Thing();
th1.x=8;
th2.x=10;
println(th1.x);
println(th2.x);
}
}
class Thing{
public Thing() {
x=0;
}
public static int x;
}
private
1、实例变量在第一个类里面直接声明 private static int counter
2、在第一个类里面创建一个方法可以让另一个类访问到x 【public incrementor() 】
2、在另一个类中创建一个实例 count1\count2
3、在另一个类中饮用实例变量 counter.neatvalue
import acm.program.*;
public class incrementor {
public incrementor() {
counter=1;
}
public incrementor(int startvalue) {
counter=startvalue;
}
public int neatvalue() {
int temp=counter;
counter++;
return(temp);
}
private static int counter;
}
class usercounter extends ConsoleProgram {
public void run() {
incrementor count1= new incrementor();
incrementor count2= new incrementor(1000);
println("five values for count1: ");
countFiveTimes(count1);
println("five values for count2: ");
countFiveTimes(count2);
println("five another values for count1: ");
countFiveTimes(count1);
}
private void countFiveTimes(incrementor counter) {
for(int i=0;i<5;i++) {
println(counter.neatvalue());
}
}
}
3、local var
在方法里面赋值,不能改变也不能被方法之外引用
4、instant var VS class var
在一个类里面可以由多个值
VS
在一个类里面只有一个值