Page 1 of 2 12 LastLast
Results 1 to 20 of 26
Like Tree2Likes

Thread: Understanding getters, setters, and constructors

  1. #1
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Understanding getters, setters, and constructors

    For the Product Class, The book says, "For each instance variable, a get method returns the data that's stored in the instance variable, and a set method assigns a new data to the instance variable."

    The get method is a straight forward no brainer, but assigns a new data to the instance variable? I don't understand what that means. In any case, will the following two code samples do the exact same thing:

    Java Code:
    import java.text.NumberFormat;
    
    public class Product {
    
    	//instance variables:
    	private String itemName;
    	
    	//default constructor:
    	public Product()
    	{
    		itemName = "";		
    	}
    	
    	//the set and get methods for the itemName variable
    	public void setItemName(String itemName)
    	{
    		this.itemName = itemName;
    	}
    	public String getItemName()
    	{
    		return itemName;
    	}
    	
    }//end of class body
    Java Code:
    import java.text.NumberFormat;
    
    public class Product {
    
    	//instance variables:
    	private String itemName;
    	
    	//default constructor:
    	public Product()
    	{
    		itemName = "";
    	}
    	
    	//Overload Constructor:
    	public Product(String itemName)
    	{
    		this.itemName = itemName;
    	}
    	
    }//end of class body
    Finally, in what situations would I need or not need a default constructor, assuming I've also coded another constructor that accepts parameters?

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,422
    Blog Entries
    7
    Rep Power
    28

    Default Re: Understanding getters, setters, and constructors

    If you set itemName in a constructor, that's all fine, but if you don't have an appropriate setter method defined in that class, you can never set itemName anytime later ...

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  3. #3
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: Understanding getters, setters, and constructors

    Quote Originally Posted by JosAH View Post
    If you set itemName in a constructor, that's all fine, but if you don't have an appropriate setter method defined in that class, you can never set itemName anytime later
    Okay, I think I have a better understanding about the importance of setters, but I still can't think of a situation of where I would need to include both an overload constructor and get and set methods. For example, would the overload constructor in the following code be necessary or redundant:
    Java Code:
    import java.text.NumberFormat;
    
    public class Product {
    
    	//instance variables:
    	private String itemName;//string cannot be resolved to a type
    	private String description;
    	private double price;
    	
    	//default constructor:
    	public Product()
    	{
    		itemName = "";
    		description = "";
    		price = 0;
    	}
    
    	//overload constructor:
    	public Product(String itemName, String description, double price)
    	{
    		this.itemName = itemName;
    		this.description = description;
    		this.price = price;
    	}
    
    	//the set and get methods for the itemName variable
    	public void setItemName(String itemName)
    	{
    		this.itemName = itemName;
    	}
    	public String getItemName()
    	{
    		return itemName;
    	}
    	
    	//the get and set methods for the description variable
    	public void setDescription(String Description)
    	{
    		this.description = description;
    	}
    	public String getDescription()
    	{
    		return description;
    	}
    	
    	//the get and set methods for the price variable
    	public void setPrice(double Price)
    	{
    		this.price = price;
    	}
    	public double getPrice()
    	{
    		return price;
    	}
    	
    }//end of class body

  4. #4
    claudiu's Avatar
    claudiu is offline Member
    Join Date
    May 2016
    Location
    RO
    Posts
    5
    Rep Power
    0

    Default Re: Understanding getters, setters, and constructors

    There is no a situation where you need to include both
    and in the case you provide setter methods is not necessary to provide the overloaded constructor.

    On the other hand, as JosAH mentioned, if you don't have an appropriate setter method defined in the class, you can never set itemName anytime later.
    This approach is used when you want to create an immutable class.

    Off-topic, I notice a design error in your setters methods.
    The assignment there has no effect.

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: Understanding getters, setters, and constructors

    Off-topic, I notice a design error in your setters methods.
    The assignment there has no effect.
    Can you explain what the problem is?
    If you don't understand my response, don't ignore it, ask a question.

  6. #6
    claudiu's Avatar
    claudiu is offline Member
    Join Date
    May 2016
    Location
    RO
    Posts
    5
    Rep Power
    0

    Default Re: Understanding getters, setters, and constructors

    I will explain for setDescription(String Description),

    Java Code:
    //the get and set methods for the description variable
        public void setDescription(String Description)
        {
            this.description = description;
        }
    he is assigning to the instance variable description it's own value.
    Notice the uppercase D from the parameter declaration.

    same is valid for setPrice(String Price) method.
    Norm and JosAH like this.

  7. #7
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: Understanding getters, setters, and constructors

    Lets say I create a new class instance:
    Java Code:
    //Create a object:
    Product product;
    product = new Product("java", "code, not the coffee", 5.00);
    After that, there are two ways I could code my setter:
    Java Code:
    public void setItemName(String itemName)
    	{
    		this.itemName = itemName;
    	}
    	/*
    	//alternate way to write set method:
    	public void setItemName(String name)
    	{
    		itemName = name;
    	}
    	*/
    	public String getItemName()
    	{
    		return itemName;
    	}
    To call the setter method the alternate way, the syntax would be:
    Java Code:
    product.setItemName(name);
    But if I code my setter the other way (with the this. keyword), what would replace the name argument in the setItemName method call?

  8. #8
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Understanding getters, setters, and constructors

    Quote Originally Posted by claudiu View Post
    There is no a situation where you need to include both
    Assuming I understand what you are saying, I disagree. In most situations you should provide getters and setters.
    Otherwise, you expose the implementation details of the class. Overriding the constructor also saves time in initializing
    those values. In the case of immutable classes, setters should not be provided (and defensive copies of objects
    should be returned in the getters).

    And quite often one may want to use those same getters and setters from within the class. This confines changes
    to just a few locations in case the internals of the class change.

    @OP. Typically, a standard method for initializing various combinations of default values is the following:

    Java Code:
    public Product() {
           this ("", "", 0);
    }
    
    public Product(String itemName, String description) {
         this (itemName, description, 0);
    }

    etc.


    Regards,
    Jim
    Last edited by jim829; 05-28-2016 at 04:41 PM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  9. #9
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: Understanding getters, setters, and constructors

    Quote Originally Posted by jim829 View Post
    @OP. Typically, a standard method for initializing various combinations of default values is the following:

    Java Code:
    public Product() {
           this ("", "", 0);
    }
    
    public Product(String itemName, String description) {
         this (itemName, description, 0);
    }
    Assuming you're telling me how to correctly write a constructor or function/method definition (and not a class instance object since you didn't use the new keyword anywhere in the code you just posted), thanks, but you didn't answer my question. My question had nothing to do with defining or initializing a function/method.

    I was asking for the syntax to call a setter method that uses the this keyword:
    Java Code:
    public void setItemName(String name)
        {
            itemName = name;
        }
    product.setItemName(name);//method call statement
    Java Code:
    public void setItemName(String itemName)
        {
            this.itemName = itemName;
        }
    //what is the syntax for the statement that calls this version of the setter method?

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: Understanding getters, setters, and constructors

    what is the syntax for the statement that calls this version of the setter method?
    From your post #7
    To call the setter method ..., the syntax would be:
    Java Code:
    product.setItemName(name);
    The same code would be used to call either version of the setter method.
    If you don't understand my response, don't ignore it, ask a question.

  11. #11
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Understanding getters, setters, and constructors

    I was not responding to your question. I was responding to another's post which said you never needed
    to use both setters and getters. All I was showing you in the last part was to demonstrate how to
    have other partial constructors make use of the full (all value) constructor when only initializing some of
    the values.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  12. #12
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: Understanding getters, setters, and constructors

    Quote Originally Posted by Norm View Post
    The same code would be used to call either version of the setter method.
    So would it be:
    Java Code:
    product.setItemName(this.itemName);
    or
    Java Code:
    product.setItemName(itemName);
    ?

  13. #13
    claudiu's Avatar
    claudiu is offline Member
    Join Date
    May 2016
    Location
    RO
    Posts
    5
    Rep Power
    0

    Default Re: Understanding getters, setters, and constructors

    Quote Originally Posted by jim829 View Post
    I was not responding to your question. I was responding to another's post which said you never needed
    to use both setters and getters. All I was showing you in the last part was to demonstrate how to
    have other partial constructors make use of the full (all value) constructor when only initializing some of
    the values.

    Regards,
    Jim
    I assume it was for my #8 post.
    You misunderstood my saying. I wasn't refer to the fact to provide both setters and getters.
    I was referred to the overloaded constructor vs. setters.

    Java Code:
    //overload constructor:
        public Product(String itemName, String description, double price) {
            this.itemName = itemName;
            this.description = description;
            this.price = price;
        }
    vs.

    Java Code:
    public void setItemName(String itemName) {
            this.itemName = itemName;
        }
         
        public void setDescription(String Description) {
            this.description = description;
        }
         
        public void setPrice(double Price) {
            this.price = price;
        }
    If I am not wrong this was the initial questions:
    but I still can't think of a situation of where I would need to include both an overload constructor and get and set methods.
    (see #3)

    I agree, overriding the constructor saves time in initializing the values.
    And in practice I am using this approach.

    But once again, I am not sure if there is a situation when you are force to provide both (overload constructor and setter methods).

  14. #14
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Understanding getters, setters, and constructors

    Normally, use the second approach. "this" only works with instance fields. So most of the time leave off "this" as it is not necessary.
    If you are in a static context, "this" will cause a compiler error. And if the itemName is a local variable,
    "this" will also cause a compiler error. The only time you normally qualify an instance field with this is when
    you have a local variable of the same name. Then you may need to differentiate them.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  15. #15
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: Understanding getters, setters, and constructors

    Java Code:
    product.setItemName(this.itemName);
    As Jim said, this is only used to provide access to instance fields.

    IMO You should NEVER have a local variable with the same name as an instance variable. Having the same name can be confusing.
    The local variable will shadow the instance variable.

    Java Code:
    class TestClass {
      String itemName = "instance"; // instance field
    
      public void someMethod() {
         String itemName = "local"; // local variable
         ...
         Product product = new Product();
         product.setItemName(this.itemName);  // call with instance variable
         product.setItemName(itemName);        // call with local variable
       }
    }
    If you don't understand my response, don't ignore it, ask a question.

  16. #16
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Understanding getters, setters, and constructors

    Quote Originally Posted by claudiu View Post
    But once again, I am not sure if there is a situation when you are force to provide both (overload constructor and setter methods).
    Naturally no one is forcing you to do both. But often it can be useful to do both. The overloaded constructor allows me to
    selectively create objects with varying degrees of initialization when I can rely on default values for some of the instances.
    And the getters and setters allow me to retrieve or set the values later as required without exposing implementation details.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  17. #17
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: Understanding getters, setters, and constructors

    I have more experience with C++ than I do with Java. As a result, I'm used to how C++ defines methods either below the main method, in child classes, (or both), and then calls all of the methods in the main method. But judging from the errors in the following Java code, it seems that Java doesn't follow that same pattern:
    Java Code:
    import java.text.NumberFormat;
    
    public class Product {
    
    	//instance variables:
    	private String itemName;//string cannot be resolved to a type
    	private String description;
    	private double itemPrice;
    	
    	//default constructor:
    	public Product()
    	{
    		itemName = "";
    		description = "";
    		itemPrice = 0.0;
    	}
    	
    	//overload constructor:
    	public Product(String itemName, String description, double itemPrice)
    	{
    		this.itemName = itemName;
    		this.description = description;
    		this.itemPrice = itemPrice;
    	}
    	
    	//the set and get methods for the itemName variable
    	public void setItemName(String name)
    	{
    		itemName = name;
    	}	
    	public String getItemName()
    	{
    		return itemName;
    	}
    	
    	//the get and set methods for the description variable
    	public void setDescription(String desc)
    	{
    		description = desc;
    	}
    	public String getDescription()
    	{
    		return description;
    	}
    	
    	//the get and set methods for the price variable
    	public void setPrice(double price)
    	{
    		itemPrice = price;
    	}
    	public double getPrice()
    	{
    		return itemPrice;
    	}	
    		
    }//end of class body
    
    //Create a class instance object:
    Product product;
    product = new Product("java", "code, not the coffee", 5.00);
    
    //Calling methods:
    product.printToConsole();
    
    //print data directly to the console:
    public void printToConsole()//Syntax error on token "printToConsole", AnnotationName expected after this token
    {
    	System.out.println(itemName + " Costs $" + itemPrice);
    	String message = "Item Name: " + product.getItemName() + "\n";
    	System.out.println(message);
    }//Syntax error, insert "}" to complete ClassBody
    So how does Java do things differently?

    Also, is my overload constructor serving any significant purpose in this code?

  18. #18
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: Understanding getters, setters, and constructors

    the errors in the following Java code
    Please copy the full text of the error message and paste it here. It has important info about the error.
    If you don't understand my response, don't ignore it, ask a question.

  19. #19
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Understanding getters, setters, and constructors

    Quote Originally Posted by Sam_JavaTheHut5580 View Post
    Also, is my overload constructor serving any significant purpose in this code?

    Your constructor allows the instantiation with arguments in line 60. And as I said in an earlier message,
    your default constructor is best done as follows:

    Java Code:
    public Product() {
         this("", "", 0.0);
    }
    Now the default constructor will invoke the overloaded constructor and initialize your values.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  20. #20
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: Understanding getters, setters, and constructors

    Quote Originally Posted by Norm View Post
    Please copy the full text of the error message and paste it here. It has important info about the error.
    For future reference, remember that it is my practice to place error messages as code comments on the lines that they occur on when I post my code. For the code in post #17, the full text of the error messages are the comments on lines 66 and 71.

    Quote Originally Posted by jim829 View Post
    Now the default constructor will invoke the overloaded constructor and initialize your values.
    Initialize them to what? Testing the printToConsole() method is almost pointless if all I have to print out is two empty strings and a 0. But I guess that doesn't really matter either if I don't even know how to invoke a Java class, so I'll ask again:

    If C++ has most or all methods defined outside the main method, and then called sequentially in the main method, how does Java do things differently? I need to understand that before I get into inheritance.

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 11
    Last Post: 06-04-2015, 04:37 PM
  2. Getters and setters
    By Erre in forum New To Java
    Replies: 10
    Last Post: 10-25-2012, 08:30 PM
  3. Confused about getters and setters
    By jnjh in forum New To Java
    Replies: 8
    Last Post: 05-03-2011, 07:12 AM
  4. Getters and Setters
    By lheviathan in forum New To Java
    Replies: 4
    Last Post: 11-02-2009, 01:47 AM
  5. Getters and Setters
    By Charliestons in forum New To Java
    Replies: 10
    Last Post: 09-12-2008, 10:57 PM

Posting Permissions

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