Loading

Constructor

  • A constructor is a method used to initialize the object.
  • It is automatically called when a class is instantiated.

 Key Points:-

  • A constructor must have the same name as of class name.
  • Constructors do not have any return type.
  • It can't be final, static, abstract, or synchronized.

Types of Constructor


       1. Default Constructor:-

  • Constructors declared without parameters are called Default constructors
  • It provides default values i.e.- 0, NULL to objects.

Syntax:

Class_name ( ) 
{  
    // body
}

 Example:

package quipohouse;
class Message {
	Message() {
		System.out.println("QUIPO HOUSE");
	}

	public static void main(String[] args) {
		Message obj = new Message();
	}
}

Output:

QUIPO HOUSE

2 . Parameterized Constructor:-

  • Constructors declared with parameters are called Parameterized constructors.
  • It provides different values to objects.

Syntax:

Class_name(para1,para2 )
{  
     // body
}

Example:

package quipohouse;
public class Identifier {
	String msg, msg1;
	Identifier(String msg, String msg1) {
		// This keyword refer current class object
		this.msg = msg;
		this.msg1 = msg1;
	}

	void message() {
		System.out.println(msg + "" + msg1);
	}

	public static void main(String[] args) {
		Identifier obj = new Identifier(" Message ", " msg ");
		obj.message();
	}
}

Output:

Message  msg