Home
| | Sitemap
||Page number :12
Constructors
You have already studied in depth about methods, classes and Java. Now we will study about “Constructors”, which are an important part of java programs.
Definition-A constructor of a class is a special function which is automatically called when the object of the class is called. A constructor makes our work easier by initializing objects at their creation. The most important question is how? We will now study it.
Special Features of Constructors—
These are some really important characteristics of Constructors. Read them very carefully.
- Constructors have the same name as that of class.
- They don’t have any return type (void, int).
- Constructors cannot be inherited. “Super” keyword is used to call the parent class constructor.
Declaration of Constructors---
class any { public any() //Constructor { /* Body of Constructor Body continues …. */ } }
Lets study a simple example of a class “Calc”.
class calc { int n,n2,sum; public calc() //Class Constructors { n=15; n2=20; }
public void sum() { sum=n+n2; System.out.println("Sum is "+sum); } }
class apply10 { public static void main(String args[]) { calc obj=new calc(); //Constructor called.... obj.sum(); } }
Have a look at the constructor’s body, you can see two statements. { n=15; n2=20; } Here when the constructor was called the two variables were automatically initialized. Thus we mentioned earlier that “A constructor makes our work easier by initializing objects at their creation.”
Two Types of Constructors--- 1.Default Constructor. 2.Parameterized Constructor
Default Constructor---A “default constructor” is a constructor with no parameters.(You are already familiar with the concepts of parameters. The class constructed in the previous page contains a default constructor “calc”.
Parameterized Constructor---A “parameterized constructor” is a constructor with parameters. The way of declaring and supplying parameters is same as that with methods. Study this example—
class cons_param {
int n,n2; int sum,sub,mul,div; public cons_param(int x,int y) { n=x; n2=y; }
public void opr() { sum=n+n2; sub=n-n2; mul=n*n2;
div=n/n2;
System.out.printn("Sum is "+sum); System.out.printn("Difference is "+sub); System.out.printn("Product is "+mul); System.out.printn("Quotient is "+div); } }
class apply11 { public static void main(String args[]) { cons_param obj=new cons_param(6,17); obj.opr(); } }

page 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29