sy04_1:使用修饰符

有时需要公开一些变量和方法,有时需要禁止其他对象使用变量和方法,这时可以使用修饰符来实现这个目的。常用的修饰符有: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


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值