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:
- It has no return type.
- It is called through the new keyword.
- A constructor has the same name as the class.
- Generally public or default.
For example:
- class mp {
- Mp() {}
- }
Types of constructor
There are two types of constructor as given below:
- Default constructor
- Parameterized constructor
1. Default Constructor
- class mp {
- mp() {
- System.out.println(“znl”);
- }
- }
2. Parameterized Constructor
- class mp {
- mp(int x) {
- System.out.println(“xml”);
- }
- }
Constructor Overloading
- class mp {
- mp() {
- System.out.println("yahoo");
- }
- mp(int a) {
- System.out.println("you have just selected constructor with integer value: " + a);
- }
- mp(float a) {
- System.out.println("you have just selected constructor with float value: " + a);
- }
- mp(int a, int b) {
- System.out.println("you have just selected constructor with integer values: " + a + " and " + b);
- }
- mp(int a, float b) {
- System.out.println("you have just selected constructor with integer value: " + a + " and float value: " + b);
- }
- }
- class sp {
- public static void main(String[] ab) {
- mp a1 = new mp();
- new mp(3);
- new mp(3, 2);
- new mp(3.3 f);
- new mp(4, 8.9 f);
- }
- }
Output

Comments
Join the conversation! Your thoughts help the community grow.