Credits

Tuesday, June 22, 2010

Java's Accessor and Mutator Methods

To further illustrate Java's capability for modular programming, accessor ( use of setName() ) and mutator ( use of getName() ) methods can be further used.

Below is a program that breaks down the task into several methods. 
[+/-] show/hide


/*Sample program on methods
*/
import java.io.*;
public class TuitionMethodv2 {
double tuition;
double tunits;
double unitprice;

String name;
String course;


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

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

System.out.println("Input your name:");
String myname=br.readLine();

System.out.println("Input your course:");
String mycourse=br.readLine();

System.out.println("Input tuition units:");
String totalunits=br.readLine();
double mytunits=Double.parseDouble(totalunits);

System.out.println("Input unit price:");
String unitrate=br.readLine();
double myuprice=Double.parseDouble(unitrate);

myObject.setName(myname);
myObject.setCourse(mycourse);
myObject.setUnitPrice(myuprice);
myObject.setTotalUnits(mytunits);

System.out.println("Name: "+myObject.getName());
System.out.println("Course: "+myObject.getCourse());
System.out.println("Total Units: "+myObject.getTotalUnits());
System.out.println("Unit Price: "+myObject.getUnitPrice());
System.out.println("Due Tuition: "+myObject.compute());



}

void setName(String xname){
name=xname;
}

void setCourse(String xcourse){
course=xcourse;
}

void setUnitPrice(double xunitprice){
unitprice=xunitprice;
}

void setTotalUnits(double xtunits){
tunits=xtunits;
}

String getName(){
return name;
}

String getCourse(){
return course;
}

double getUnitPrice(){
return unitprice;
}

double getTotalUnits(){
return tunits;
}

double compute()
{ tuition= tunits*unitprice;
return tuition;}

}


AddThis