有时需要公开一些变量和方法,有时需要禁止其他对象使用变量和方法,这时可以使用修饰符来实现这个目的。常用的修饰符有:public,private,protected,package,static,final,abstract等。
1. 程序功能:通过两个类 StaticDemo、KY4_1 来说明类变量与对象变量,以及类方法与对象方法的区别。
2. 编写源程序 KY4_1.java,程序源代码如下。
class StaticDemo {
static int x;
int y;
public static int getX() {
return x;
}
public static void setX(int newX) {
x = newX;
}
public int getY() {
return y;
}
public void setY(int newY) {
y = newY;
}
}
public class KY4_1 {
public staticvoid main(String[] args) {
System.out.println("类变量x="+StaticDemo.getX());
System.out.println("对象变量y="+StaticDemo.getY());
StaticDemo a=new StaticDemo();
StaticDemo b=new StaticDemo();
a.setX(1);
a.setY(2);
b.setX(3);
b.setY(4);
System.out.println("类变量a.x="+a.getX());
System.out.println("对象变量a.y="+a.getY());
System.out.println("类变量b.x="+b.getX());
System.out.println("对象变量b.y="+b.getY());
}
}
3.编译并运行程序 KY4_1.java,看看该程序是否有错?如果有错请在实验报告中指出出错的地方,出错的原因,并给出修改意见以及程序正确运行的结果。
改正后的代码如下:
public class KY4_1 {
public static void main(String[] args) {
System.out.println("类变量x="+StaticDemo.getX());
System.out.println("对象变量y="+StaticDemo.getY());
StaticDemo a= new StaticDemo();
StaticDemo b= new StaticDemo();
a.setX(1);
a.setY(2);
b.setX(3);
b.setY(4);
System.out.println("类变量a.x="+a.getX());
System.out.println("对象变量a.y="+a.getY());
System.out.println("类变量b.x="+b.getX());
System.out.println("对象变量b.y="+b.getY());
}
}
class StaticDemo {
static int x;
static int y;
public static int getX() {
return x;
}
public static void setX(int newX) {
x = newX;
}
public static int getY() {
return y;
}
public void setY(int newY) {
y = newY;
}
}
答:运行有错;因为y不是static声明的变量,所以不可以在未定义前调用,所以System.out.println("对象变量y="+StaticDemo.getY()); 有错。应该在类StaticDemo中定义y为int static y;且类方法public static int getY()即可。
正确运行结果:
类变量x=0
对象变量y=0
类变量a.x=3
对象变量a.y=4
类变量b.x=3
对象变量b.y=4