Learn Java for Web Development

(Tina Meador) #1

386 APPENDIX A: Introduction to Java


Method Overloading


Each method has a name and a formal parameter list. The name of the method and its formal
parameter list together with the type and the order of the parameter in the parameter list constitute
the signature of the method. As long as the method signatures differ, more than one method can
have the same method name. Such methods with the same method names and different signatures
are called overloaded methods, and this phenomenon is called method overloading. Thus,
overloaded methods are the methods that have the same name but a different parameter list. Listing
A-8 shows five implementations of the method methodA.


Listing A-8. Overloaded MethodA( )



  1. void methodA{(int a, double b) }

  2. int methodA(int a) { return a; }

  3. int methodA() { return 1; }

  4. long methodA(double a, int b) { return b; }

  5. long methodA(int c, double d) { return a; } // Not ok.


   The first four implementations of method are overloaded correctly, each time with
a different parameter list and, therefore, different signatures.
 The declaration on line 5 has the same signature methodA(int, double) as the
declaration on line 1. Changing just the return type is not enough to overload a
method; the parameter list in the declarations must be different.

Note Only methods declared in the same class and those that are inherited by the class can be overloaded.

Arrays


An array is a data structure that is comprised of a fixed number of data elements essentially of
the same data type. Any element in the array can be accessed using an index. The first element is
always at index 0, and the last element is at index n-1, where n is the value of the length field in the
array. In Java, arrays are objects where all elements in the array can be of a specific primitive data
type or of a specific reference type. Listing A-9 declares references that refer to the array objects.


Listing A-9. Array Declarations


int [] intArray;
ClassA[] classAArray ;


The two declarations in Listing A-9 declare intArray and classAArray to be reference variables that
can refer to arrays of int values and arrays of ClassA objects. An array can be constructed for a fixed
number of elements of a specific type, using the new operator. Given the previous array declarations,
the arrays can be constructed as follows:


intArray = new int[10]; // array for 10 integers
classAArray = new ClassA[5]; // array of 5 objects of ClassA

Free download pdf