Credits

Saturday, November 27, 2010

Java's Use of Constructors

A Java constructor is used to create an instance of a class or whenever we make an example or object of a class. When we instantiate without the parameters, Java crate a constructor but with an empty body. However, when we initialize values to our class, we pass these values through a set of parameters.

However, you have to remember that Java constructors must  have the exact name of their respective classes. Further, they must not return any value.

The program below is the version for computing pay with the application of constructor.

[+/-] show/hide


/*Sample program on methods
*/
import java.io.*;
public class ComputePayCallingConstructor {


public static void main(String args[]) throws IOException{
double xhrate;
double xhrsworked;
double xtdeductions;
String name;
String position;
String payperiod;

BufferedReader br= new BufferedReader(new InputStreamReader(System.in));

System.out.println("Input employee's name:");
name=br.readLine();


System.out.println("Input employee's position:");
position=br.readLine();

System.out.println("Input payroll period:");
payperiod=br.readLine();

System.out.println("Input employee's hourly rate:");
xhrate=Double.parseDouble(br.readLine());

System.out.println("Input employee's hours worked:");
xhrsworked=Double.parseDouble(br.readLine());

System.out.println("Input employee's total deductions:");
xtdeductions=Double.parseDouble(br.readLine());

ComputePayConstructor myObject=new ComputePayConstructor(xhrate,xhrsworked,xtdeductions);

System.out.println("Payroll Period:"+payperiod);
System.out.println("Name:"+name);
System.out.println("Position:"+position);
System.out.println("Hourly Rate:"+xhrate);
System.out.println("Hours worked:"+xhrsworked);
System.out.println("Employee's Net Pay: "+myObject.compute());
}
}

/*Sample program on methods
*/
//called by ComputePayCallingConstructor
public class ComputePayConstructor {

double netpay;
double hrate;
double hrsworked;
double tdeductions;

ComputePayConstructor(double hr, double hw, double td)
{
hrate=hr;
hrsworked=hw;
tdeductions=td;
}


double compute()
{ netpay= (hrate*hrsworked) - tdeductions;
return netpay;
}

}

AddThis