Wednesday, 28 August 2013

Constructors In Java


//Program Starts Here
import java.util.Scanner;
class cons
{
double length, breadth, height;
cons() /*default constructor when no value is passed*/
{
length=0;
breadth=0;
height=0;
}
cons(double l) /*constructor when a single value is passed*/
{
length=l;
}
cons(double l, double b) /*constructor when two values are passed*/
{
length=l;
breadth=b;
}
cons(double l, double b, double h) /*constructor when three values are passed*/
{
length=l;
breadth=b;
height=h;
}
double call() /*method to call a constructor according to number of values passed*/
{
double ans=-1;
if(length==0 && breadth==0 && height==0)
{
System.out.print("Constructor With No Parameter Called Here");
}
if(length>0 && breadth==0 && height==0)
{
System.out.print("\nConstructor With 1 Parameter  Called Here");
ans=length*length*length;
}
else if(length>0 && breadth>0 && height==0)
{
System.out.print("\nConstructor With 2 Parameters Called Here");
ans=length*breadth;
}
else if(length>0 && breadth>0 && height>0)
{
System.out.print("\nConstructor With 3 Parameters Called Here");
ans=length*breadth*height;
}
return(ans);
}
}
class abc
{
public static void main(String arg[])
{
cons X=new cons(); /*Passing No Value*/
System.out.println("\nDefault values");
System.out.println("Length : "+X.length);
System.out.println("Breadth: "+X.breadth);
System.out.println("Height : "+X.height);
cons Y=new cons(8); /*Passing single value*/
System.out.println("\nObjectY==>");
System.out.println("Length : "+Y.length);
System.out.println("Breadth: "+Y.breadth);
System.out.println("Height : "+Y.height);
cons Z=new cons(3,14); /*Passing two values*/
System.out.println("\nObjectZ==>");
System.out.println("Length : "+Z.length);
System.out.println("Breadth: "+Z.breadth);
System.out.println("Height : "+Z.height);
cons T=new cons(5.7,43,4.45); /*Passing three values*/
System.out.println("\nObjectT==>");
System.out.println("Length : "+T.length);
System.out.println("Breadth: "+T.breadth);
System.out.println("Height : "+T.height);
cons P=new cons(4,7); /*Change number of parameters here and you will get different constructor called*/
System.out.println("\nYour answer: "+P.call());
}
}
//Program Ends Here


For More Java Programs Click Here

Thanks For Visiting....

No comments:

Post a Comment