Thursday, April 21, 2011

Types of Methods in java

Constructor methods allow class objects to be created with fields initialized to values as determined by the methods' parameters. This allows objects to start with values appropriate to use (eg. salary set to a base level or employeeNumber set to an incrementing value to guarantee uniqueness). For our simple box class:
public Box() {length=0;width=0;height=0;} // default is point
public Box(int l,int w,int h) // allows giving initial size
  {length=l; width=w; height=h;}
Note that there is no class keyword or return datatype keyword. Also the method name is the same as the class name. This is what marks the fragment as a constructor method. If no constructor method is defined for a class, a default constructor is automatically used to initialize all fields to 0, false or unicode(0) as appropriate to the datatype.
One clever programming device is to declare the constructor with no parameters as private and use it to initialize all properties. Then other constructors can first call it using this() and then do their own specific property validations/initialization.
Accessor (or observer) methods read property (ie. field variable) values and are conventionally named getFoobar() or whatever the property is called.
Mutator (or transformer) methods set property values and are often named setFoobar() etc. Mutators can be used to ensure that the property's value is valid in both range and type.
It is good programming practice to make each property in a class private and include accessor and mutator methods for them. This is an example of object encapsulization. The exceptions to writing accessor/mutator methods for each property is for those that are used only within the class itself or for properties that are set in more complex ways.
Helper methods are those routines that are useful within the class methods but not outside the class. They can help in code modularization. Normally they are assigned private access to restrict use.
Recursive methods are methods that are defined in terms of themselves. A classic recursion is factorials where n factorial is the product of positive integer n and all the products before it down to one. In Java this could be programmed as:
class Factorial
{
  int factorial(int n)
  {
   if (n==1){return 1};
   return (n*factorial(n-1));
  }
}
Caution: This short method is not very well written as negative and floating calling parameters are illegal in factorials and will cause problems in terminating the loop. Bad input should always be trapped.

No comments:

Post a Comment

Chitika