Friday 24 May 2013

CONSTRUCTORS IN JAVA

Constructors are those specialized functions in a class, that automatically get invoked as soon as we declare any object of that class. Compiler itself provides a default constructor, if we don't explicitly define a constructor of a class. The constructors can be overloaded as simple functions. In order to use call a constructor of a super-class class we use super keyword, it's use is clearly mentioned in the following program. The comments in this program will definitely help you to have a better understanding of this program.



Source Code:-
/********************************************************************************/
/*program illustrating the basics of constructors
 * illustrates constructor overloading
 * use of super keyword
 */
class javaapp {

public static void main(String[] args) {

class_b b1=new class_b();

double ans1=b1.addition(10,20);
double ans2=b1.addition(30,40,50);

System.out.println("answer1 = "+ans1+"\nanswer2 = "+ans2+"\n");

class_b b2=new class_b(5);
class_b b3=new class_b(5,3);

}

}



class class_b extends class_a{
private double result;
/*super keyword is used to specify the immediate superclass*/
/*default constructor of class_b*/
public class_b()
{
/*default constructor of class_a will be called as no other constructor is specified*/
System.out.println("Default Constructor of class_b called\n");
}
/*Single Argumented constructor class_b*/
public class_b(int a)
{
super(a,a);
/*now double argumented constructor of class_a will be called*/
System.out.println("Single Argumented constructor class_b called\n");
}
/*Double Argumented constructor class_b */
public class_b(int a,int b)
{
super(a);
/*single argumented constructor of class_a will be called */
System.out.println("Double Argumented constructor class_b called\n");
}
/*overloaded function*/
public double addition(int x,int y,int z)
{
/*
function overloading
function with different arguments
function name is same but argument list or argument type should be diff.
in other way we can say function name can be same but argument signature should be different 
*/
result =x+y+z;
return result;
}

}


class class_a {
private double result;
/*default constructor of class_a*/
public class_a()
{
System.out.println("Default Constructor of class_a called");
}
/*Single Argumented constructor class_a*/
public class_a(int a)
{
System.out.println("Single Argumented constructor class_a called");
}
/*Double Argumented constructor class_a */
public class_a(int a,int b)
{
System.out.println("Double Argumented constructor class_a called");
}
public double addition(int x,int y)
// function with two arguments
{
result =x+y;
return result;
}

}
/*******************************************************************************/

Output:-


No comments:

Post a Comment