The this Keyword


The this Keyword

The this keyword is a reference to the current object and is implicitly passed to every nonstatic method. The this keyword can be used to clear up any ambiguities that might exist due to naming conflicts and so forth.

Example: Using the this Keyword

The this keyword is typically used when writing constructors, but can be applied to any situation where ambiguity is present. There is a school of thought in Java programming that the variable names in a constructor input parameter list should match the names of the fields of the class. Since you are now dealing with two variables with the same name , you need to use the this keyword to differentiate between the input parameter variable and the field.

As an example, let's rewrite the Species class so the input parameter names in the Species class constructor are the same as the field names. The this keyword tells the compiler that the name and molarMass variables to the left of the equals sign refer to the class fields.

 public class Species2 {   private String name;   private double molarMass;   public Species2(String name, double molarMass) {     this.name = name;     this.molarMass = molarMass;   }   public String getName() {     return name;   }   public double getMolarMass() {     return molarMass;   }   public static void main(String args[]) {     Species2 ob = new Species2("unobtainium", 0.99);     System.out.println("Molar mass of " +              ob.getName() + " is "+ob.getMolarMass());   } } 

Output ”

 Molar mass of unobtainium is 0.99 


Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net