0

When do we use the this.field phrase? This code will work either way, and I understand the difference between static and nonstatic methods and fields, but I'm not sure when to use this. and when to just use the field name. As an example, a simplified excerpt of my code is below.

public class ShoppingCart { 
    private String customerName;

    public ShoppingCart(String name){
        customerName = name;
    }
    public String getCustomerName(){
        return customerName;
    }

is there a generally accepted/better practice for when to use this.customerName = name and just using customerName = name?

And a bonus question, when referring to these fields further down in the same class, is it a better programming practice to just name the field, or name the getter? If I wanted to print out something like

System.out.println("customer name is: " + );

is is better to end that with just customerName, or should I use getCustomerName so that I don't accidentally mess with the field itself?

  • 2
    Does this answer your question? [When should I use "this" in a class?](https://stackoverflow.com/questions/2411270/when-should-i-use-this-in-a-class) – blackbrandt Jul 30 '21 at 17:32

0 Answers0