Credits

Saturday, July 3, 2010

Another Java Constructor

As posted about Java's constructors, it can be used to initialize variables but may be later replaced by new values.

See sample program.
[+/-] show/hide



import java.io.*;
public class Household {
int numOccupants;
double annualIncome;
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)
    x.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