Translate

Saturday 20 December 2014

Constructors in Java

Constructors are special methods that are called automatically when an object of the class is created. Constructor have same name as the class and they dont have a return type not even void.
Basically there are 3 types of constructors

  1. Default
  2. Parameterized
  3. Copy-constructor
Default Constructor:- This constructor takes no argument. It is called when an object is created without any explicit initialization.
              Money m1 = new Money();
If we have not defined any constructor then default constructor is provided by java.

Parameterized Constructor:- This constructor is called when object is created  and initialised with some value at the time of creation.
               Money m1 = new Money(1000,20);

Copy Constructor:- This constructors is called when an object is created. It's initialised with some other object of class at the time of creation.
               Money m1 = new Money(1000,20);             
               Money m2 = new Money(m1);

Definition of constructor looks like this
class Money
{
    private int rs, paisa;
    public Money()
    {
         rs = paisa = 0;
    }
    public Money (int r, int p)
    {
         rs = r;
         paisa = p;
    }

    public Money (Money m)
    {
         rs = m.rs;
         paisa = m.paisa;
    }
    public void set (int r, intp)
}

Always remember that we can call a method from an another method of the same class, simply by using it's name. 

No comments:

Post a Comment

Total Pageviews