1.当一个变量对于类的对象来说是共同的,这个时候需要使用一个概念:static
2.用到的关键字是”static”
3.在Java中,static关键字被用在三种场景
- 用于实例变量
- 用于方法
- 用于一段代码
4.Static Variables
5.Static Methods
6.Static Block
Retail Application – Case Study
class Customer{
private int customerId = 1000;
public Customer(){
customerId++;
}
public int getCustomerId(){
return customerId;
}
}
class Retail{
public static void main(String args[]){
Customer custObj1= new Customer();
System.out.println("Customer Id:" + custObj1.getCustomerId());
Customer custObj2= new Customer();
System.out.println("Customer Id:" + custObj2.getCustomerId());
}
}
Output:
Customer Id: 1001
Customer Id: 1001
The Customer Id has not been incremented. What is the reason for this output?
customerId is an instance variable of Customer class and it will be created
separately for each and every object of Customer class. Hence each time an object
of Customer class is created, constructor is called and customerId will be initialized
to 1000 and will be incremented by 1 in the constructor as a result for all the
objects customerId will remain as 1001.
Hence we need to have a variable common to all the objects of Customer class
Compare this with C language wherein global variables are used for sharing common data across functions in a file.
Static Variables
Class loading happens the moment the class is referenced in a program. A class can be referenced in the following situations:
JVM will load the class when it is referenced.