A constructor is similar to method and it is invoked at the time creating an object of the class, it is generally used to initialize the instance variables of a class. The constructors have same name as their class.
Return type of a constructor
- A constructor doesn’t have any return type.
- The data type of the value retuned by a method may vary, return type of a method indicates this value.
- A constructor doesn’t return any values explicitly, it returns the instance of the class to which it belongs.
Example
Following is an example of a constructor in 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");
}
}Output
Tutorialspoint
Example
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();
}
}Output
Value of age: 25