码家

Web Platform, Cloud and Mobile Application Development

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  1. 构造函数是一种特殊的方法,和class有相同的名字
  2. 构造函数是用来初始化类的实例变量的
  3. 构造函数有两种类型:默认的构造函数和参数化的构造函数
ØConstructor is a special method that has the same name as that of a class
ØThe constructor is used to initialize the instance variables of the class 
ØTypes of  constructors:
§Default constructor
§Parameterized constructor
 

Parameterized constructor will be discussed along with method overloading

Default Constructor

ØIf the programmer does not code the constructor explicitly, the system provides a default constructor
§This initializes the instance variables to their default values
ØProgrammer can redefine the default constructor
§Such a constructor does not take any arguments
§The instance variables can be initialized by the user explicitly inside this constructor
 

Retail Application – Case Study

class Customer{

  private int customerId;

  public int getCustomerId(){

  return customerId;

  }

}

class Retail{

public static void main(String args[]){

  Customer custObj=new Customer();

  System.out.println("Customer Id:"+

  custObj.getCustomerId());

}

}

Output:

  Customer Id: 0

Note that the system provides a default constructor

 

class Customer{

  private int customerId;

  public Customer(){

  customerId=1000;

  }

  public int getCustomerId(){

  return customerId;

  }

}

class Retail{

public static void main(String args[]){

  Customer custObj=new Customer();

  System.out.println("Customer Id:“+  custObj.getCustomerId());

  }

}

Retail Application – Case Study 

class Customer{

  private int customerId;

  public Customer(){

  customerId=1000;

  }

  public int getCustomerId(){

  return customerId;

  }

}

class Retail{

public static void main(String args[]){

  Customer custObj=new Customer();

  System.out.println("Customer Id:“+  custObj.getCustomerId());

  }

}

Output:

  Customer Id: 1000

Note that the default constructor is redefined

 

 

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