码家

Web Platform, Cloud and Mobile Application Development

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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

ØThe concept of static is used whenever data which is common to the objects of the class is required
ØKeyword to be used is “static”
ØIn Java, static keyword can be used in 3 scenarios:
§For instance variables
§For methods
§For a block of code

Compare this with C language wherein global variables are used for sharing common data across functions in a file.

Static Variables

ØStatic variables are also called as a class variables
ØThey are different from  instance variables of the class
ØStatic members represent data that is common to the entire class
ØA single copy of the data will be shared by all instances of the class
ØThey are initialized at class load time. If not explicitly initialized during declaration, they will have default values
ØSyntax for declaring static variable:<<Access specifier>><<static>> <<datatype>> <<variable name>>
 

Class loading happens the moment the class is referenced in a program. A class can be referenced in the following situations:

1.When an object of the class is created or
2.When a method of a class is invoked with/without objects (non static/static methods respectively) or
3.When an instance variable/class variable of a class is accessed with/without objects

 

JVM will load the class when it is referenced.

posted on 2011-05-22 09:30  海山  阅读(215)  评论(0编辑  收藏  举报