Credits

Friday, November 27, 2009

Use of Java's Static Methods

Java uses methods to break down tasks into smaller units. Another type of method is the static method. To access a static method, one has to type, ClassName.MethodName(). With static methods, we need static variables.

Do check the sample program for the use of static methods.



[+/-] show/hide




import java.io.*;
public class ChangeV2 {


static double cost;
static double tax;
static double payment;
public static void main(String args[]) throws IOException{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String str;
String prodname;
double xcost=0.0;
double totalcost=0.0;
double change=0.0;
double xpayment=0.0;
System.out.println("Input Product name:");
prodname=br.readLine();

System.out.println("Input Item Cost: ");
str=br.readLine();
xcost=Double.parseDouble(str);
ChangeV2.setCost(xcost);
ChangeV2.setTax(xcost);
totalcost=ChangeV2.getCost()+ChangeV2.getTax();
System.out.println("Tax: "+ChangeV2.getTax());
System.out.println("Total Costs:"+totalcost);
System.out.println("Input Payment: ");
str=br.readLine();
xpayment=Double.parseDouble(str);
ChangeV2.setPayment(xpayment);
change=ChangeV2.getPayment()-totalcost;

System.out.println("Change:"+change);

}


public static double getCost()
{ return cost;}
public static void setCost(double x)
{ cost=x;}
public static double getPayment()
{ return payment;}
public static void setPayment(double x)
{ payment=x;}
public static void setTax(double x)
{ tax=x*.06;}

public static double getTax()
{ return tax;}


}





AddThis