Credits

Friday, December 4, 2009

Java's Constructor

Constructors in Java allow physical creation of objects. We normally initialize them to default values. These may contain or not arguments as we create objects.

Take not however, that constructors follow the name of their respective class name.

Below is an example of a constructor application.



[+/-] show/hide


/**
*
* @author Rose
*/
import java.io.*;
public class Household {
int numOccupants;
double annualIncome;

//this a constructor
Household()
{ numOccupants=1;
annualIncome=0;}

public static void main(String args[]) throws IOException{

BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
Household x=new Household();
String str;
int numOcc;
double xincome=0.0;

System.out.println("use of Constructors:");
System.out.println("Number of Occupants "+x.getOccupants());
System.out.println("Annual Income"+x.getIncome());

System.out.println("After Use:");
System.out.println("Input number of occupants :");
numOcc=Integer.parseInt(br.readLine());

System.out.println("Input Annual Income: ");
str=br.readLine();
xincome=Double.parseDouble(str);

x.setOccupants(numOcc);
x.setIncome(xincome);

if (numOcc<=0)
x.numOccupants=1;
if (xincome<0.0)
annualincome=0.0;
System.out.println("Number of Occupants "+x.getOccupants());
System.out.println("Annual Income"+x.getIncome());

}


double getIncome()
{ return this.annualIncome;}

void setOccupants(int x)
{ this.numOccupants=x;}

double getOccupants()
{ return this.numOccupants;}

void setIncome(double x)
{ annualIncome=x;}

}

AddThis