静态方法和静态字段

package test;

public class StaticTest {

	public static void main(String[] args) {
		// fill the staff array with three Employee objects
		Employee[] staff = new Employee[3];
		
		staff[0] = new Employee("Tom",40000);
		staff[1] = new Employee("Dick",50000);
		staff[2] = new Employee("Harry",60000);
		
		// print out information about all employee objects
		for (int  i = 0; i < staff.length; i++)
		{
			Employee e = staff[i];
			e.setId();
			System.out.println("name=" + e.getName() + ", id=" + e.getId() +
                                                        ", salary=" + e.getSalary());			         
		}
		
		int n = Employee.getNextId();
		System.out.println("Next available id=" + n);

	}
}

class Employee
{
	private String name;
	private double salary;
	private int id;
      //静态字段属于这个类,而不属于单个的对象。类的对象共享这个静态字段。
	private static int nextId = 1;
	
	public Employee(String n,double s){
		name = n;
		salary =s;
		id = 0;	
	}
	public String getName()
	{
		return name;
	}
	public void setName(String name){
		this.name = name;
	}
	public double getSalary(){
		return salary;
	}
	public void setSalary(double salary){
		this.salary = salary;
	}
	public int getId(){
		return id;
	}
	public void setId()
	{
		// set id to next avilable id
		id = nextId;
		nextId++;
	}
      //静态方法是不向对象施加操作的方法,不能访问实例字段,只能访问类自身中的静态字段。
	public static int getNextId()
	{
		return nextId; //return static field
	}
	
	public static void main(String[] args){
		Employee e = new Employee("Harry",50000);
		System.out.println(e.getName() + "\t" + e.getSalary());
	}
}

  运行结果:

name=Tom, id=1, salary=40000.0
name=Dick, id=2, salary=50000.0
name=Harry, id=3, salary=60000.0
Next available id=4

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值