[CSC 204] Something That you may Like
Andrew J. Pounds
pounds at theochem.mercer.edu
Thu Feb 10 15:29:38 EST 2011
While I know that some of you haven't started on your ShippingCrate
file, others are in the midst of writing lots of methods to do various
things. Undoubtedly some of you are fighting with names of variables
and how to keep instance variables separate from local variables and
parameters. Here is a neat little thing that you can do in Java that
might help you keep some of this stuff straight.
Let's assume that we have a private instance variable in out class
called diameter and that we need to write a method to assign a value to
it. In class I showed you how to do something like.
public void assignDiameter( double d){
diameter = d;
}
The cleaner and MUCH PREFERRED way to do this is something like...
|public void assignDiameter( double diameter){
this.diameter = diameter;
}
|
In the method above the this.diameter refers to the INSTANCE VARIABLE
called diameter and the diameter in the method call is a parameter. If
you do this the Java compiler will also help you catch some silly
mistakes that you might make related to your instance variables.
--
Andrew J. Pounds, Ph.D. (pounds at theochem.mercer.edu)
Associate Professor of Chemistry and Computer Science
Mercer University, Macon, GA 31207 (478) 301-5627
More information about the csc204
mailing list