构造器看起来像方法(method),但实际上并不是方法,因为它没有返回类型。构造器必须与类(class)具有相同的名字,以下是一个简单的构造器实例。
public class MyClass{
//This is the constructor
MyClass(){
}
..
}
构造器通常用于初始化新建的对象,如下例,调用了前面定义的MyClass()构造器,来初始化obj这个对象。
MyClass obj = new MyClass()
public class Hello {
String name;
//Constructor
Hello(){
this.name = "BeginnersBook.com";
}
public static void main(String[] args) {
Hello obj = new Hello();
System.out.println(obj.name);
}
}
Output:
BeginnersBook.com
构造器类型分为默认的(default),无参数的(No-arg),有参数的(Parameterized)。
1. 默认的构造器。若在你的代码中没有定义构造器,则在编译.java文件的时候,java编译器会在编译的时候自动在你的代码中插入构造器,如下图。若你的代码中定义了构造器,则java编译器不会再为你添加构造器。
2. 无参数的构造器。以下为实例。
class Demo
{
public Demo()
{
System.out.println("This is a no argument constructor");
}
public static void main(String args[]) {
new Demo();
}
}
output:
This is a no argument constructor
3. 有参数的构造器。
实例1:
public class Employee {
int empId;
String empName;
//parameterized constructor with two parameters
Employee(int id, String name){
this.empId = id;
this.empName = name;
}
void info(){
System.out.println("Id: "+empId+" Name: "+empName);
}
public static void main(String args[]){
Employee obj1 = new Employee(10245,"Chaitanya");
Employee obj2 = new Employee(92232,"Negan");
obj1.info();
obj2.info();
}
}
Output:
Id: 10245 Name: Chaitanya Id: 92232 Name: Negan
实例2:在这个实例中,我们定义了一个无参数和一个有参数的构造器。当在创建对象时,若不传递参数,则无参数的构造器将被调用,若传递相应的参数,则有参数的构造器将被调用。
class Example2
{
private int var;
//default constructor
public Example2()
{
this.var = 10;
}
//parameterized constructor
public Example2(int num)
{
this.var = num;
}
public int getValue()
{
return var;
}
public static void main(String args[])
{
Example2 obj = new Example2();
Example2 obj2 = new Example2(100);
System.out.println("var is: "+obj.getValue());
System.out.println("var is: "+obj2.getValue());
}
}
Output:
var is: 10 var is: 100
实例3:以下实例将报错,因为你只定义了有参数的构造器,却在调用时调用了无参数的构造器。
class Example3
{
private int var;
public Example3(int num)
{
var=num;
}
public int getValue()
{
return var;
}
public static void main(String args[])
{
Example3 myobj = new Example3();
System.out.println("value of var is: "+myobj.getValue());
}
}
构造器重载(Constructor Overloading)。当有多个构造器具有不同的参数时,它们执行不同的功能,如下图:
参考文献:
https://beginnersbook.com/2013/03/constructors-in-java/