Java中的构造函数

构造函数是以类命名的特殊方法,没有返回类型,用于构造对象。
构造函数和方法一样,可以接受输入参数。
构造函数用于初始化对象。
抽象类也可以有构造函数。

public class Hello{
      //constructor
      public Hello(String wordToPrint){
          printHello(wordToPrint);
      }
      public void printHello(String word){
        System.out.println(word);
      }
}
//instantiates the object during creating and prints out the content
//of wordToPrint

重要的是要了解构造函数在以下几个方面与方法不同:

  • 构造函数只能使用修饰符public、private 和protected,不能声明为abstract、final、static 或者synchronized。
  • 构造函数没有返回类型。
  • 构造函数的命名必须与类名相同。在 Hello 示例中,Hello 对象的构造函数名称与类名称相同。
  • 这个关键字在构造函数中有一个另外的用法。 this.method(…) 调用当前实例上的一个方法,而 this(…) 引用当前类中具有不同签名的另一个构造函数。

构造函数也可以通过使用关键字 super 的继承来调用。

public class SuperManClass{
      public SuperManClass(){
          //some implementation
      }
      //… methods
}
public class BatmanClass extends SupermanClass{
      public BatmanClass(){
           super();
      }
      //… methods…
}
日期:2020-06-02 22:15:20 来源:oir作者:oir