*What is constructor ?
*
In Java, a constructor is a special method that is used to initialize objects when they are created.
The constructor is called when an object of a class is created.
A constructor in Java is similar to a method.
The Java compiler
provides a default
constructor if you don't
have any constructor in a
class.
Rules for creating Java constructor:
There are two rules defned for the constructor.
- Constructor name must be the same as its class name
- A Constructor must have no explicit return type
Types of Java constructors
There are two types of constructors in Java:
- Default constructor (no-arg constructor)
- Parameterized constructor
Example for constructor:
class Student {
String name;
int age;
// parameterized constructor
Student(String n, int a) {
name = n;
age = a;
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("John", 20);
System.out.println(s1.name + " " + s1.age);
}
}
Top comments (0)