java的实例变量(instant var)、类变量(class var)

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
在一个类里面只有一个值类变量和实例变量的区别

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值