Saturday 8 February 2014

Constructors

Constructors are used to initialize object at the time of creation.
syntax
    modifier className(){
    }

Here modifier is anything like private, public, protected, default. Will discuss more about modifiers in the packages section. As you see constructors don't have any return type and constructor name equals to the class name.

If you don't provide the constructor, then compiler provides the default constructor for your class.

Example
class Box{
 int width,height; 
 
 Box(){
  width = 10;
  height = 10;
 }

 public static void main(String args[]){
  Box b1 = new Box();
  System.out.println(b1.width +"\t"+b1.height);
 }
}
          

Output
10 10

          
As you see in the above program, Box() is initializing the properties for an object to 10 at the time of creation.

Overloading Constructors
Just like overloading methods, we can overload the constructors also.
Example
class Box{
 int width,height;
 
 Box(){
  width = 0;
  height = 0;
 }

 Box(int h){
  width = height = h;
 }

 Box(int w, int h){
  width = w;
  height = h;
 }

 public static void main(String args[]){
  Box b1 = new Box();
  Box b2 = new Box(15);
  Box b3 = new Box(15, 25);
  
  System.out.println(b1.width +"\t"+b1.height);
  System.out.println(b2.width +"\t"+b2.height);
  System.out.println(b3.width +"\t"+b3.height);
 }
}
   
Output
0 0
15 15
15 25
                     
Some points to Remember
1. Can we make constructor and method with the same name ?
    Yes, it is valid in Java   
  Example
class Box{
 int width,height;

 Box(){
  width = 10;
  height = 10;
 }

 void Box(){
  System.out.println(width +"\t"+height);
 } 

 public static void main(String args[]){
  Box b1 = new Box();
  System.out.println(b1.width +"\t"+b1.height);
 }
}

Output
10 10
             
2. Can constructors throw exceptions ?
Yes, Constructors are like special methods in java.

Example
   public Socket(String host,int port)throws UnknownHostException,IOException

Socket class in the java.net.Socket, throws UnknownHostException, if the IP address of the host could not be determined.
       
   

Overloading varargs                                                 Class Variables                                                 Home

No comments:

Post a Comment