Saturday, June 16, 2012

CONSTRUCTOR


Constructors
1. Constructors are "special methods" whose name is same as class name.
2. Constructors doesn't have any return type even void also.
3. Constructors will be invoked by the JVM when you are creating object.
4. Constructors can be overloaded.
5. Constructors is used to initialize objects.
Example :
class Hello
 {
  int a,b;
  Hello()
    {
     System.out.println("Iam a constructor");
     a=88;
     b=99;
    }
  Void m1()
    {
      System.out.println ("Iam a method m1");
      System.out.println ("a value is"+a);
      System.out.println ("b value is"+b);
    }
 }
class Ex1
 {
  public static void main(String as[])
   {
     Hello h= new Hello();
     h.m1();
   }
 }
Output :
        Iam a constructor
        Iam a method m1
        a value is 88
        b value is99


Constructor Overloading :
We can do the following by overloading the constructors :
1. I want to initialize different objects of a class with different set of values.
2. I want to provide different values dynamically when I'm creating the object.
Note :
» JVM inserts default constructor when there is no other constructor.
» JVM doesn't insert default constructor when the class has overloaded constructors.

this operator :
» This is a reference variable which contains object of current class.
» When you have same name for the local variables and instance variables, local variables hides the instance variables.This is called as shadowing.
» To refer the instance variable qualify the variable with "this". i.e. "this.a".

No comments:

Post a Comment