Saturday 2 March 2013

Constructors in java


A constructor is a special method of class, which is invoked automatically, whenever an object of a class is created.  It has the same name as its class and resides similar to a method.  A constructor has the following characteristics.
Ø  It doesn’t have any return type not even void
Ø  The constructor can be declared as public
Ø  It can be overloaded
Ø  It is normally used to initialize the member of the object

Different types of Constructors:
1) Default Constructor: A constructor that accepts no parameters is called the default constructor.  If no constructors are defined for a class, the Java system automatically generates the default constructor.

Example:

class Time1
{
            int hour,min,sec;
            public Time1()
            {
            hour=10;
            min=45;
            sec=23;
            }
            void printdata()
            {
            System.out.println(hour+"hours:"+min+"minutes:"+sec+"seconds");
            }
}
class const1
{
            public static void main(String[] args)
            {
                        Time1 t=new Time1();
                        t.printdata();
            }
}

O/P:    10hours:45minutes:23seconds

2) Parameterized Constructor: A constructor that takes arguments as parameters is called parameterized constructor.  If any constructors are defined by a class with the parameters, Java will not create a default constructor for the class.

Example:                                     

class Time1
{
            int hour,min,sec;
            public Time1(int h,int m,int s)
            {
            hour=h;
            min=m;
            sec=s;
            }
            void printdata()
            {
            System.out.println(hour+"hours:"+min+"minutes:"+sec+"seconds");
            }
}
class const2
{
            public static void main(String[] args)
            {
                        Time1 t=new Time1(10,9,4);
                        t.printdata();
            }
}

O/P:    10hours:9minutes:4seconds

No comments:

Post a Comment