Java 中的构造器的返回类型是什么?
构造器类似于方法,它在创建类对象时调用,通常用于初始化类的实例变量。构造器的名称与其类相同。
构造器的返回类型
- 构造器没有返回类型。
- 方法返回的值的数据类型可能不同,方法的返回类型表示该值。
- 构造器不显式返回任何值,而是返回其所属类的实例。
示例
以下是 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("Tutorialspoint"); } }
Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.
输出
Tutorialspoint
示例
class Student{ Integer age; Student(Integer age){ this.age = age; } public void display() { System.out.println("Value of age: "+this.age); } } public class GenericsExample { public static void main(String args[]) { Student std = new Student(25); std.display(); } }
输出
Value of age: 25
广告