构造函数与method相似,它在创建类的对象时被调用,通常用于初始化类的实例变量。构造函数与其类具有相同的名称。
构造函数没有任何返回类型。
方法重调的值的数据类型可能会有所不同,方法的返回类型指示此值。
构造函数不会显式返回任何值,而是会返回其所属的类的实例。
以下是java中的构造函数的示例-
public class Sample{ public Sample(){ System.out.println("Hello how are you"); } public Sample(String data){ System.out.println(data); } public static void main(String args[]){ Sample obj = new Sample("Nhooo"); } }输出结果
Nhooo
class Student{ Integer age; Student(Integer age){ this.age= age; } public void display() { System.out.println("年龄值: "+this.age); } } public class GenericsExample { public static void main(String args[]) { Student std = new Student(25); std.display(); } }输出结果
年龄值: 25