Credits

Monday, December 6, 2010

Java's Use of Constructors with Arguments

Constructors are created as means to create objects. Normally, constructors are without arguments but when we want our classes to be more interactive with one another, we allow the use of constructors with arguments to take play.


The program below shows a way for the programs to pass arguments to one constructor.

[+/-] show/hide


//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;
}

}


/*the calling program*/
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());
}
}

AddThis