Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. Java
  4. How to use setters and getters.

How to use setters and getters.

Scheduled Pinned Locked Moved Java
salestutorialhelpquestionlearning
6 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • U Offline
    U Offline
    User 12313793
    wrote on last edited by
    #1

    Hey guys. I'm having so much trouble understanding setters and getters. I've read the setter/getter chapter for our testbook multiple times and have looked up many things online but can't get it to work. It doesn't help that there are very few completed examples in my book so its hard to actually see how anything is applied in a finished state. This is one of our programs we have to do for class. We were supposed to use setters and getters, but I couldn't figure it out, so desperately created the program below to at least get the end result, albeit not with the method required. Utilizing my program below, can someone explain the basics of setters and getters and how I would apply them? Not asking for someone to do my work for me, just thought it'd give a good example for me to understand. My program basically shows a menu, a user enters how many of each product they want through keyboard input, and then the program calculates the subtotal before tax, the tax amount, and then the grand total (subtotal + tax). Pretty simple.

    public class CateringOrderApp {

    public static void main(String\[\] args) {
    	
    	Scanner keyboard = new Scanner(System.in);
    	
    	//Declares tax rate constant.
    	double SALES\_TAX\_RATE = .0875;
    	//Declares calculation variables.
    	double subtotalCost;
    	double taxAmount;
    	double totalCost;
    	//Sets constant prices for items.
    	double VEGGIE\_SANDWICH\_PRICE = 2.75;
    	double HAM\_AND\_CHEESE\_SANDWICH\_PRICE = 3.25;
    	double SPAGHETTI\_PRICE = 35.00;
    	double SALAD\_PRICE = 18.00;
    	//Declares order count for items
    	double veggieSandwichCount = 0;
    	double hamAndCheeseSandwichCount = 0;
    	double spaghettiCount = 0;
    	double saladCount = 0;
    	
    	//Displays menu
    	System.out.println("Food Item                                          Price");
    	System.out.println("--------------------------------------------------------");
    	System.out.println("Veggie Sandwich                                    $2.75");
    	System.out.println("Ham and Cheese Sandwich                            $3.25");
    	System.out.println("Spaghetti (tray serves 20)                        $35.00");
    	System.out.println("Salad (tray serves 20                             $18.00");
    	System.out.println("--------------------------------------------------------");
    	
    	//Begins to ask customer about the number of orders for each specific item.
    	System.out.println("Please enter the amount of Veggie sandwiches that yo
    
    L 1 Reply Last reply
    0
    • U User 12313793

      Hey guys. I'm having so much trouble understanding setters and getters. I've read the setter/getter chapter for our testbook multiple times and have looked up many things online but can't get it to work. It doesn't help that there are very few completed examples in my book so its hard to actually see how anything is applied in a finished state. This is one of our programs we have to do for class. We were supposed to use setters and getters, but I couldn't figure it out, so desperately created the program below to at least get the end result, albeit not with the method required. Utilizing my program below, can someone explain the basics of setters and getters and how I would apply them? Not asking for someone to do my work for me, just thought it'd give a good example for me to understand. My program basically shows a menu, a user enters how many of each product they want through keyboard input, and then the program calculates the subtotal before tax, the tax amount, and then the grand total (subtotal + tax). Pretty simple.

      public class CateringOrderApp {

      public static void main(String\[\] args) {
      	
      	Scanner keyboard = new Scanner(System.in);
      	
      	//Declares tax rate constant.
      	double SALES\_TAX\_RATE = .0875;
      	//Declares calculation variables.
      	double subtotalCost;
      	double taxAmount;
      	double totalCost;
      	//Sets constant prices for items.
      	double VEGGIE\_SANDWICH\_PRICE = 2.75;
      	double HAM\_AND\_CHEESE\_SANDWICH\_PRICE = 3.25;
      	double SPAGHETTI\_PRICE = 35.00;
      	double SALAD\_PRICE = 18.00;
      	//Declares order count for items
      	double veggieSandwichCount = 0;
      	double hamAndCheeseSandwichCount = 0;
      	double spaghettiCount = 0;
      	double saladCount = 0;
      	
      	//Displays menu
      	System.out.println("Food Item                                          Price");
      	System.out.println("--------------------------------------------------------");
      	System.out.println("Veggie Sandwich                                    $2.75");
      	System.out.println("Ham and Cheese Sandwich                            $3.25");
      	System.out.println("Spaghetti (tray serves 20)                        $35.00");
      	System.out.println("Salad (tray serves 20                             $18.00");
      	System.out.println("--------------------------------------------------------");
      	
      	//Begins to ask customer about the number of orders for each specific item.
      	System.out.println("Please enter the amount of Veggie sandwiches that yo
      
      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      Setters and Getters are used to hide the implementation of fields in an object, and just provide a convenient method to save or return a value. At its most basic level you could have something like:

      private double taxAmount;
      public double getTaxAmount()
      {
      //include more logic
      return taxAmount;
      }
      public void setTaxAmount(double value)
      {
      //include validation, logic, logging or whatever you like here
      taxAmount = value;
      }

      If the implementation of the field changes then it should only be necessary to modify the setter and getter thus avoiding changes to the code in the rest of the class.

      S 1 Reply Last reply
      0
      • L Lost User

        Setters and Getters are used to hide the implementation of fields in an object, and just provide a convenient method to save or return a value. At its most basic level you could have something like:

        private double taxAmount;
        public double getTaxAmount()
        {
        //include more logic
        return taxAmount;
        }
        public void setTaxAmount(double value)
        {
        //include validation, logic, logging or whatever you like here
        taxAmount = value;
        }

        If the implementation of the field changes then it should only be necessary to modify the setter and getter thus avoiding changes to the code in the rest of the class.

        S Offline
        S Offline
        Sherin_Mathew
        wrote on last edited by
        #3

        In Java, getter and setter are two conventional methods that are used for retrieving and updating value of a variable. The following code is an example of simple class with a private variable and a couple of getter/setter methods:

        public class SimpleGetterAndSetter {
        private int number;

        public int getNumber() {
            return this.number;
        }
        
        public void setNumber(int num) {
            this.number = num;
        }
        

        }

        The class declares a private variable, number. Since number is private, code from outside this class cannot access the variable directly, like this:

        SimpleGetterAndSetter obj = new SimpleGetterAndSetter();
        obj.number = 10; // compile error, since number is private
        int num = obj.number; // same as above

        Instead, the outside code have to invoke the getter, getNumber() and the setter, setNumber() in order to read or update the variable, for example:

        SimpleGetterAndSetter obj = new SimpleGetterAndSetter();
        obj.setNumber(10);
        int num = obj.getNumber();

        So, a setter is a method that updates value of a variable. And a getter is a method that reads value of a variable.

        L 1 Reply Last reply
        0
        • S Sherin_Mathew

          In Java, getter and setter are two conventional methods that are used for retrieving and updating value of a variable. The following code is an example of simple class with a private variable and a couple of getter/setter methods:

          public class SimpleGetterAndSetter {
          private int number;

          public int getNumber() {
              return this.number;
          }
          
          public void setNumber(int num) {
              this.number = num;
          }
          

          }

          The class declares a private variable, number. Since number is private, code from outside this class cannot access the variable directly, like this:

          SimpleGetterAndSetter obj = new SimpleGetterAndSetter();
          obj.number = 10; // compile error, since number is private
          int num = obj.number; // same as above

          Instead, the outside code have to invoke the getter, getNumber() and the setter, setNumber() in order to read or update the variable, for example:

          SimpleGetterAndSetter obj = new SimpleGetterAndSetter();
          obj.setNumber(10);
          int num = obj.getNumber();

          So, a setter is a method that updates value of a variable. And a getter is a method that reads value of a variable.

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #4

          This question was answered, by me, four years ago. Please focus on current questions, and also ensure that you are responding to the correct person.

          OriginalGriffO 1 Reply Last reply
          0
          • L Lost User

            This question was answered, by me, four years ago. Please focus on current questions, and also ensure that you are responding to the correct person.

            OriginalGriffO Offline
            OriginalGriffO Offline
            OriginalGriff
            wrote on last edited by
            #5

            Rep point hunter: he's plagiarising semi-relevant crap and trying to hide it in old posts: Plagiarism in the forums (Sherin_Mathew)[^]

            "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony AntiTwitter: @DalekDave is now a follower!

            "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
            "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

            L 1 Reply Last reply
            0
            • OriginalGriffO OriginalGriff

              Rep point hunter: he's plagiarising semi-relevant crap and trying to hide it in old posts: Plagiarism in the forums (Sherin_Mathew)[^]

              "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony AntiTwitter: @DalekDave is now a follower!

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #6

              Thanks, I didn't spot that.

              1 Reply Last reply
              0
              Reply
              • Reply as topic
              Log in to reply
              • Oldest to Newest
              • Newest to Oldest
              • Most Votes


              • Login

              • Don't have an account? Register

              • Login or register to search.
              • First post
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • World
              • Users
              • Groups