Pages

Thursday, 18 July 2013

CONSTRUCTOR


Definition - Constructor is a special type of method i e. used to initialize a newly created object & is just called after memory is allocated for object.

Rules to be followed while defining constructor
  1. It has same name as that of class.
  2. No return type should be there.
  3. Constructors can use any access modifier, including private.
Note:-  You can define method with the same name as of class. Example-

class A{
  private A()
{
// Constructor with private access modifier, it means object of class A can only be instantiated with //in the class not outside it.To instantiate from outside class you have to use static method with in // //class A.
}
public void A()
{
// Legal method
}

public static void main(String... x)
{
new A(); // anonymous object
}
}

Q1. Do constructors have  return type?
Ans. Yes. Constructors return reference of their class.
         Do some practical .

 class A{
  A( ){

return ; // will not give any error. This proves that constructors returns something.
}
public static void main( )
{
System.out.println(new A( ));  // It will print A@1270b73 (ClassName@hashcode)  constroctur
}
}


 

Blogger news

Blogroll

Most Reading

Tags