Java2all.com  

Constructor





Share This Topic -

Java supports a special type of methods, called constructor that enables an object to initialize itself when it is created.

Constructors have the same name as the class it-self.

Constructors do not specify a return type, not even void. This is because they return the instance of the class itself.

A constructor is automatically called when an object is created.

Syntax:

Constructor_name([arguments])

{

           // body

}

Constructors are generally of two types.

1.      Non-Parameterized

2.      Parameterized  

1.      Non-Parameterized:

 // Non - parameterised constructor 
class Point1
{
        int x;
        int y;
        Point1()   //constructor of class
        {
                x = 10;
                y = 20;
        }
        void display()
        {
                System.out.println("\n\n\t-----Printing the coordinates-----");
                System.out.println("\t\t\t" + x + "  " + y);
        }
}
class pointDemo
{
        public static void main(String args[])
        {
                Point1 p1 = new Point1();  // constructor will be call automatically from here
                p1.display();
        }
}        

Output:
 
-----Printing the coordinates-----
                   10   20
 
2.      Parameterized:
 // parameterised constructor
import java.util.Scanner; 
class Point2
{
        int x;
        int y;
        Point2(int a, int b)
        {
                x = a;
                y = b;
        }
        void display()
        {
                System.out.println("\n\n\t-----Printing the coordinates-----");
                System.out.println("\t\t\t" + x + "  " + y);
        }
}
class pointDemo
{
        public static void main(String args[])
        {
                int i,k;
                Scanner s = new Scanner(System.in);
                System.out.print("Enter int value for i : ");
                i = s.nextInt();
                System.out.print("Enter int value for k : ");
                k = s.nextInt();
                Point2 p1 = new Point2(i,k);
                p1.display();
        }
}        

Output:
 
Enter int value for i : 10
Enter int value for k : 20
-----Printing the coordinates-----
                   10   20