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

 

 

相关文章:

  • 2022-12-23
  • 2022-01-26
  • 2021-12-03
  • 2022-01-31
  • 2022-01-08
  • 2021-11-09
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-27
  • 2021-07-10
  • 2022-12-23
  • 2021-12-21
  • 2022-12-23
  • 2021-11-11
相关资源
相似解决方案