在Java中,构建对象。每次创建一个新对象时,都会调用至少一个构造函数 。每个类都有一个构造函数,但如果你不明确地创建一个构造函数,编译器会为你构建一个构造函数。关于 构造函数有很多规则,让我们关注基本声明规则。下面是一个简单的例子:
class Tets{
protected Test() { } // this is Test's constructor
protected void Test() { } // this is a badly named,
// but legal, method
}
首先要注意的是,构造函数看起来像一个非常多的方法。 A 关键的区别是构造函数永远不会有返回类型......永远! 构造函数声明可以拥有所有正常的访问修饰符,它们可以接受参数(包括var-args),就像方法一样。其他BIG 规则,了解构造函数是他们必须具有相同的名称 它们声明的类。构造函数不能被标记为静态(它们 毕竟与对象实例化有关),它们不能被标记为最终的 或抽象(因为它们不能被覆盖)。下面是一些合法的和非法 构造函数声明:
class Foo2 {
// legal constructors
Foo2() { }
private Foo2(byte b) { }
Foo2(int x) { }
Foo2(int x, int... y) { }
// illegal constructors
void Foo2() { } // it's a method, not a constructor
Foo() { } // not a method or a constructor
Foo2(short s); // looks like an abstract method
static Foo2(float f) { } // can't be static
final Foo2(long x) { } // can't be final
abstract Foo2(char c) { } // can't be abstract
Foo2(int... x, int t) { } // bad var-arg syntax
}
访问https://java.net/downloads/jfjug/SCJP%20Sun%20Certified%20Programmer%20for%20Java%206-0071591060.pdf
我没有看到任何显式的构造函数定义。 –