- 构造函数是一种特殊的方法,和class有相同的名字
- 构造函数是用来初始化类的实例变量的
- 构造函数有两种类型:默认的构造函数和参数化的构造函数
Parameterized constructor will be discussed along with method overloading
Default 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