Objects and Classes
Object
this
How to use the this keyword
- Since Java implicitly uses the this keyword for instance variables and methods, you don't need to explicitly code it unless a parameter has the same name as an instance variable.
- If you use the this keyword to call another constructor, the statement must be the first statement in the constructor.
The syntax for using the this keyword
this.variableName // refers to an instance variable of the current object this(argumentList); // calls another constructor of the same class this.methodName(argumentList) // calls a method of the current object objectName.methodName(this) // passes the current object to a method ClassName.methodName(this) // passes the current object to a static method
How to refer to instance variables with the this keyword
public Product(String code, String description, double price) { this.code = code; this.description = description; this.price = price; }
How to refer to methods
public String getFormattedPrice() { NumberFormat currency = NumberFormat.getCurrencyInstance(); return currency.format(this.getPrice); }
How to call a constructor using the this keyword
public Product() { this("", "", 0.0); }
How to send the current object to a method
public void print() { System.out.println(this); }
How to send the current object to a static method
public void save() { ProductDB.saveProduct(this); }