What is constructor?

A constructor is a special type of method, of a class, that initializes the object of that type. It is an instance method that usually has the same name as the class.
Important points about constructors:
  1. It has no return type.
  2. It is called through the new keyword.
  3. A constructor has the same name as the class.
  4. Generally public or default.
For example:
  1. class mp {
  2. Mp() {}
  3. }

Types of constructor

There are two types of constructor as given below:
  1. Default constructor
  2. Parameterized constructor

1. Default Constructor

A "default constructor" refers to a null constructor that is automatically generated by the compiler, if no constructors have been defined for the class.
A programmer-defined constructor that takes no parameters, is also called a default constructor.
For example:
  1. class mp {
  2. mp() {
  3. System.out.println(“znl”);
  4. }
  5. }

2. Parameterized Constructor

It is a type of constructor that requires the passing of parameters on the creation of the object.
For example:
  1. class mp {
  2. mp(int x) {
  3. System.out.println(“xml”);
  4. }
  5. }

Constructor Overloading

In Java, a constructor can be overloaded as a feature, of object-oriented programming.
Whenever multiple constructors are needed, they are implemented as overloaded methods. It allows more than one constructor inside the class, with a different signature.
  1. class mp {
  2. mp() {
  3. System.out.println("yahoo");
  4. }
  5. mp(int a) {
  6. System.out.println("you have just selected constructor with integer value: " + a);
  7. }
  8. mp(float a) {
  9. System.out.println("you have just selected constructor with float value: " + a);
  10. }
  11. mp(int a, int b) {
  12. System.out.println("you have just selected constructor with integer values: " + a + " and " + b);
  13. }
  14. mp(int a, float b) {
  15. System.out.println("you have just selected constructor with integer value: " + a + " and float value: " + b);
  16. }
  17. }
  18. class sp {
  19. public static void main(String[] ab) {
  20. mp a1 = new mp();
  21. new mp(3);
  22. new mp(3, 2);
  23. new mp(3.3 f);
  24. new mp(4, 8.9 f);
  25. }
  26. }

Output

Output