构造函数与方法相似,但在以下方面有所不同。
它们没有任何返回类型。
构造函数的名称与类的名称相同。
每个类都有一个构造函数。如果我们未为类明确编写构造函数,则Java编译器将为该类建立默认构造函数。
每次创建一个新对象时,将至少调用一个构造函数。
一个类可以具有多个构造函数。
class A {
public int a;
//default constructor
public A() {
this(-1);
}
//parameterized constructor
public A(int a) {
this.a = a;
}
}
public class Tester {
public static void main(String[] args) {
//new object created using default constructor
A a1 = new A();
System.out.println(a1.a);
//new object created using parameterized constructor
A a2 = new A(1);
System.out.println(a2.a);
}
}输出结果
-1 1