如何用Java编写构造函数名称?

在Java中声明构造函数与方法类似。在用Java命名类的构造函数时,您需要牢记以下几点。

  • 构造函数的名称应与类名称(以及访问说明符)相同(大小写相同)。

  • 构造函数不应具有任何返回类型。

  • 构造函数不能是静态的,最终的,抽象的和同步的。

示例

以下Java程序是构造函数的示例。

public class Sample {   Sample() {
      System.out.println("This is an example of a constructor");	   
   }
   public static void main(String args[]) {
      new Sample();
   }
}

输出结果

This is an example of a constructor