Coders Packet

Constructor In Java

By Rakesh Jat

In Java Programing language The main purpose of constructors is to set the initial state of an object when the object is created by using the new operator.

syntax of a constructor:

access_modifier class_Name (parameter_list) throws_Exception
  { // Constructor code

Constructor declarations are similar like method declarations.

1. Modifiers other than an access modifier are not permitted in the constructor header. For accessibility modifiers for constructors.

2. Constructors cannot return a value and, do not specify a return type, not even void, in the constructor header.

3. The constructor name must be the same as the class name.

4. The constructor is called when an object of a class is created.

5.It calls a default constructor if there is no constructor available in the class.  Java compiler provides a default constructor by default

A constructor that has no parameters is called a no-argument constructor.


public class Name {
 Name() { 
// No-argument constructor System.out.println("No_Argument_Constructor"); } void Name() {
System.out.println("In Method"); } public static void main(String arg[])
{ new Name().Name();
} }

Output from the program:
In Method

Download Complete Code


No comments yet