Results 1 to 13 of 13
Like Tree2Likes
  • 2 Post By Junky

Thread: get and set methods...can someone plese explain?

  1. #1
    toppcon is offline Member
    Join Date
    May 2011
    Posts
    46
    Rep Power
    0

    Default get and set methods...can someone plese explain?

    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?

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    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:
    Java 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;
            }
        }
    }
    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.
    yellowledbet and sunde887 like this.

  3. #3
    pbrockway2 is online now Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,574
    Rep Power
    12

    Default

    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.

  4. #4
    toppcon is offline Member
    Join Date
    May 2011
    Posts
    46
    Rep Power
    0

    Default

    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()?

  5. #5
    toppcon is offline Member
    Join Date
    May 2011
    Posts
    46
    Rep Power
    0

    Default

    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:

    Java 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
    	 			
           
       }
    	}
    And the Invoice class:

    Java 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;
         }
    
            }
    Can someone look at this and give me some insight?

  6. #6
    pbrockway2 is online now Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,574
    Rep Power
    12

    Default

    Quote Originally Posted by toppcon View Post
    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()?
    Such a private variable would not be accessible outside the class. To change or read its value you would need something public: a setter() or getter() method.

  7. #7
    toppcon is offline Member
    Join Date
    May 2011
    Posts
    46
    Rep Power
    0

    Default

    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:

    Java 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
    	   }
    	}
    Then the Invoice Class:

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

  8. #8
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    You call the getInvoice method but what do you do with the returned value? Also why have you made everything static?

  9. #9
    toppcon is offline Member
    Join Date
    May 2011
    Posts
    46
    Rep Power
    0

    Default

    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.

  10. #10
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    Quote Originally Posted by toppcon View Post
    I made the getInvoice method void and got rid of the return
    That was not the solution the getInvoice method is a getter, so it actually gets something and returns it back to the caller. What you then have to do is decide what to do with the returned value. HINT: assign it to a variable so you can use it.

  11. #11
    toppcon is offline Member
    Join Date
    May 2011
    Posts
    46
    Rep Power
    0

    Default

    Quote Originally Posted by Junky View Post
    That was not the solution the getInvoice method is a getter, so it actually gets something and returns it back to the caller. What you then have to do is decide what to do with the returned value. HINT: assign it to a variable so you can use it.
    So, if I change :
    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;

    }
    And Place the outprintln in the main to output message and return message and then assign it to?

  12. #12
    toppcon is offline Member
    Join Date
    May 2011
    Posts
    46
    Rep Power
    0

    Default

    Like this:

    message=myInvoice.getInvoice();
    Sytem.out.println(message);
    ?

  13. #13
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,792
    Rep Power
    25

Similar Threads

  1. Replies: 8
    Last Post: 04-17-2012, 12:00 AM
  2. Anyone can explain this?
    By kazumahits in forum New To Java
    Replies: 1
    Last Post: 03-08-2011, 03:03 AM
  3. Replies: 2
    Last Post: 12-13-2010, 02:34 PM
  4. Replies: 3
    Last Post: 12-13-2010, 08:22 AM
  5. Replies: 8
    Last Post: 06-24-2010, 09:59 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •