I have a project that requires a get and set method. I have read my text book and searched the web. I can't find anything that I can fully understand. Can someone tell me why you use a get method and a set method?
Printable View
I have a project that requires a get and set method. I have read my text book and searched the web. I can't find anything that I can fully understand. Can someone tell me why you use a get method and a set method?
When you create a class the standard practice is to make your instance variables private. Therefore you cannot access them outside the class directly. Instead you make use of accessor (get/set) methods.
Why?
I can think of two reasons and they both have to do with control over the variables.
You have a name. How would you like it if someone could just change your name without consulting you? Therefore you make the name private and if someone wanted to change your name, they would have to consult you first.
The other reason is that you can control what values are assigned to your variables. For example:
In the case of the public variable there is no control over what value is assign to it. Whereas the second value can only be accessed via the setter method which checks if the new value is positive or not.Code:class Foo {
public int valueMustBePositive = 0;
private int secondValueMustBePositive = 0;
public void setValue(int val) throw InvalidArgumentException {
if(val < 0) {
throw new InvalidArgumentException("Value must be positive");
} else {
secondValueMustBePositive = val;
}
}
}
I think of classes as modelling things - so a Person class might be a programming model of a person.
It turns out to be helpful for this model to be based on behaviour rather than state. I am less concerned with whether a person's name is a String field, or is stored in a database or anything else. What is important is that I can set the name to what I want and get the name when I need it. The ability of a Person instance to set its name to something or the ability to return what its name is, is what I am calling behaviour. The methods that express this behaviour (setName(String) and getName()) are what I might make public while the details of what the methods do - to the state: the String or database etc - would be private.
These methods are often called setters and getters.
Having public setters/getters and private implementation that deals with state has a couple of advantages that occur to me off the top of my head:
(1) My Person class can be used by any class that wants to deals with named things, not just people. These other classes do not have to be concerned with the details of state like whether there is a String holding the name or some other mechanism.
(2) Since the classes using my Person class do not have access directly to the state I can do things like check input when those classes invoke a Person instance's behaviour. For instance if someone says "setName(null);" I can throw an IllegalArgumentException instead of allowing my person to become anonymous.
So, we use set and get to have better control of vars? Can't I just stick my int into a private variable and that would accomplish the same thing? Or does it also have to do with it takes more code to use a private variable than a set()?
My other problem is trying to rap my head around this assgnmnt: I have a InvoiceApp class that has the main and calls the methods and a validator class that checks input and a Invoice class that does the calculations. I have to use only the subtotal and customerType for parameters for the Invoice constructor along with using a get and set method, and the validator class was written and compiled already-working, and I have to use the InvoiceApp class to call the methods and do the clean-up work. my code so far is:
InvoiceApp Class:
And the Invoice class:Code:
public class InvoiceApp
{
public static void main(String[] args)
{
String message;
// display a welcome message
System.out.println("Welcome to the Invoice Total Calculator");
System.out.println(); // print a blank line
Scanner sc = new Scanner(System.in);
String choice = "y";
while(choice.equalsIgnoreCase("y"))
{
// get user entries
String customerType = Validator.getString(sc,
"Enter customer type (r/c): ");
double subtotal = Validator.getDouble(sc,
"Enter subtotal: ", 0, 10000);
}
Invoice myInvoice=new Invoice();
myInvoice.getInvoice();//get formatted output in a string for printing
}
}
Can someone look at this and give me some insight?Code:
public class Invoice{
double percent;
double currency;
String sSubtotal;
String sCustomerType;
public String setCustType(String customerType, double subtotal){
// calculate the discount amount and total
double discountPercent = getDiscountPercent(subtotal, customerType);
double discountAmount = subtotal * discountPercent;
double total = subtotal - discountAmount;
// format the values
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
String sSubtotal = currency.format(subtotal);
String sCustomerType = "";
if (customerType.equalsIgnoreCase("r"))
sCustomerType = "Retail";
else if (customerType.equalsIgnoreCase("c"))
sCustomerType = "College";
return customerType;
}
public String getInvoice(double discountPercent, double discountAmount, double total, double subtotal){ // output formatted invoice
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
String sDiscountPercent = percent.format(discountPercent);
String sDiscountAmount = currency.format(discountAmount);
String sTotal = currency.format(total);
// format and display the results
String message = "Subtotal: " + sSubtotal + "\n"
+ "Customer type: " + sCustomerType + "\n"
+ "Discount percent: " + sDiscountPercent + "\n"
+ "Discount amount: " + sDiscountAmount + "\n"
+ "Total: " + sTotal + "\n";
System.out.println();
System.out.println(message);
Scanner sc = new Scanner(System.in);
System.out.print("Continue? (y/n): ");
String choice = sc.next();
System.out.println();
return message;
}
static double getDiscountPercent(double subtotal, String type)
{
double discountPercent = 0.0;
if (type.equalsIgnoreCase("r"))
{
if (subtotal >= 500)
discountPercent = .2;
else if (subtotal >= 250 && subtotal < 500)
discountPercent =.15;
else if (subtotal >= 100 && subtotal < 500)
discountPercent =.1;
else if (subtotal < 100)
discountPercent =.0;
}
else if (type.equalsIgnoreCase("c"))
{
discountPercent = .2;
}
else
discountPercent = .05;
return discountPercent;
}
}
I have cleaned up my code and my output is not printing to the screen. I ran a dummy out.print in the getCustType and the values of sCustomerType and subtotal were right. But when I call the getInvoice method, the values do not follow. Can someone help me figure this out? do I need to use a setter method?
Here is my code:
Main method:
Then the Invoice Class:Code:public class InvoiceApp
{
public static void main(String[] args)
{
String message;
double discountPercent=0;
double discountAmount=0;
double total=0;
String customerType="";
double subtotal=0;
String sCustomerType="";
// display a welcome message
System.out.println("Welcome to the Invoice Total Calculator");
System.out.println(); // print a blank line
//get customer type
Invoice.getCustType(sCustomerType, subtotal);
//get invoice output
Invoice.getInvoice(sCustomerType, customerType, discountPercent, discountAmount, total, subtotal);//get formatted output in a string for printing
}
}
Code:public static String getCustType(String sCustomerType, double subtotal){
Scanner sc = new Scanner(System.in);
String choice = "y";
while(choice.equalsIgnoreCase("y"))
{
// get user entries
String customerType = Validator.getString(sc,
"Enter customer type (r/c): ");
subtotal = Validator.getDouble(sc,
"Enter subtotal: ", 0, 10000);
if (customerType.equalsIgnoreCase("r")){
sCustomerType = "Retail";
}else if (customerType.equalsIgnoreCase("c")){
sCustomerType = "College";
}
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
return sCustomerType;
}
//output formatted invoice
public static String getInvoice(String sCustomerType, String customerType, double discountPercent, double discountAmount, double total, double subtotal){
// calculate the discount amount and total
discountPercent = getDiscountPercent(subtotal, customerType);
discountAmount = subtotal * discountPercent;
total = subtotal - discountAmount;
System.out.println("D%: "+discountPercent+"D$: "+discountAmount+"ST: "+subtotal+"T: "+total);
// format the values
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
String sDiscountPercent = percent.format(discountPercent);
String sDiscountAmount = currency.format(discountAmount);
String sTotal = currency.format(total);
String sSubtotal = currency.format(subtotal);
// format and display the results
String message = "Subtotal: " + sSubtotal + "\n"
+ "Customer type: " + sCustomerType + "\n"
+ "Discount percent: " + sDiscountPercent + "\n"
+ "Discount amount: " + sDiscountAmount + "\n"
+ "Total: " + sTotal + "\n";
System.out.println();
System.out.println(message);
return message;
}
static double getDiscountPercent(double subtotal, String type) {
double discountPercent = 0.0;
if (type.equalsIgnoreCase("r"))
{
if (subtotal >= 500)
discountPercent = .2;
else if (subtotal >= 250 && subtotal < 500)
discountPercent =.15;
else if (subtotal >= 100 && subtotal < 500)
discountPercent =.1;
else if (subtotal < 100)
discountPercent =.0;
}
else if (type.equalsIgnoreCase("c"))
{
discountPercent = .2;
}
else
discountPercent = .05;
return discountPercent;
}
}
You call the getInvoice method but what do you do with the returned value? Also why have you made everything static?
I just had an assignment to make everything static...I just did it out of a habit, I changed everything to non-static now. I made the getInvoice method void and got rid of the return, but I still am not getting any values to console.
Sorry about starting new thread about this same prob. never again.
So, if I change :
And Place the outprintln in the main to output message and return message and then assign it to?Quote:
public String getInvoice(String sCustomerType, double subtotal, double discountPercent, double discountAmount, double total){ // output formatted invoice
System.out.println("D%: "+discountPercent+"D$: "+discountAmount+"ST: +subtotal+"T: "+total);
// format the values
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
String sDiscountPercent = percent.format(discountPercent);
String sDiscountAmount = currency.format(discountAmount);
String sTotal = currency.format(total);
String sSubtotal = currency.format(subtotal);
// format and display the results
String message = "Subtotal: " + sSubtotal + "\n"
+ "Customer type: " + sCustomerType + "\n"
+ "Discount percent: " + sDiscountPercent + "\n"
+ "Discount amount: " + sDiscountAmount + "\n"
+ "Total: " + sTotal + "\n";
return message;
}
Like this:
message=myInvoice.getInvoice();
Sytem.out.println(message);
?
See posts at for same(??) problem: Having problems with output to console....help!