Constructors.

It is a special function that will be having same name as class name which will be called immediately after creating the object. Purpose of constructor: To initialize instance variables.
Program:

Below is an example program on how to write a constructor

    class Pen
       {
	int nInk;
	boolean bcap_open;
	public Pen() //constructor
	{
		nInk=100;
		bcap_open=false;
	}
       }

Properties of a constructor:

1) Most of the times constructor will be public. Note: We may have "private" constructors also. Will be discussed in singleton design pattern.
2) Constructor will not have any "return" type.
3) Constructor will be having same name as class name. Note: Having a return type for a constructor will not give any error, but it will not be treated like a constructor, rather it will be treated like a normal method.

Life cycle of the constructor:

->Constructor will be called only after creating the object. ->"new" operator will create the objects, not the constructor ->Constructors are used to initialize the object, and to initialize instance variables.
Note: If you make private constructors then we cannot create objects for that class from outside world.
Program: Write a program to find the area of a rectangle by passing length and breadth values to the constructor.
Rectangule object
File name : MainClass.java
Recangle Program
Program: Write a program which contains 2 methods, one to add two integers and other to add 2 strings.
2methods
File name : MainClass.java
             class Math
             {
	        public void addInt(int i,int j)
	        {
		System.out.println(i+j);
	        }
	        public void addString(String s,String t)
	        {
		System.out.println(s+t);
	        }
             }
              public class MainClass
               {
	        public static void main(String[] args)
	         {
		  Math m=new Math();
		  m.addInt(3,4);
		  m.addString("hello","Bye");
	        }
            }

Problem with above program:
Even though above program works fine, there is a problem with it. Imagine what will happen if we want to add 2 floats, 2 doubles, 2 chars, 2 longs and so on, then the programmer will add 4 more methods with names addFloat(), addDobule(), addChar(), and addLong().
So now the person who is using that class has to remember too many method names which may irritate the programmer. Though all the methods are doing same functionality (adding) still we are giving different names and complicating it. One solution for this problem is giving same method name for all 6 methods so that the user of this class will have to remember just only one method name.