Saturday 6 January 2018

4.3 Constructor

Constructor : 
 A method with the same name of class is known as constructor.

Thumb rules for constructor -
1. Constructor is a method
2. Constructor have same name as class
3. Constructor will never return any value therefore no return type is required.
4. Constructor will automatically called once you create the object of the class
5. Constructor allocates the memory to the object.
6. We can have more than one constructor in a class by using constructor overloading
7. You can't call a constructor expicitly
8. Implicit conversions are possible in constructors.
9. You can initialize default values of variables.




Constructor example

 class constructor_example
{
public static void main (String args[])
{
A obj=new A(); //Default constructor
A obj1=new A(2); //Constructor with one parameter
}
}

class A
{
public A()
{
System.out.println("Default constructor");
}

public A(int i)
{
System.out.println("Constructor with one parameter");
}

public A(double d)
{
System.out.println("Constructor with double");
}
}

No comments:

Post a Comment