Method Overloading Methods of the same name can be declared in the same class for different sets of parameters As the number, types and order of the parameters When an overloaded method is called, the compiler selects the appropriate method by examining the number, types and order of the arguments in the call. Method overloading is used to create several methods with the same name Perform the same or similar tasks on different types or different numbers of arguments.
public class MethodOverload { public static void main(String[] args) { System.out.printf("Square of integer 7 is %d%n", square(7)); System.out.printf("Square of double 7.5 is %f%n", square(7.5)); } public static int square(int intValue) { System.out.printf("%nCalled square with int argument: %d%n",intValue); return intValue * intValue; } public static double square(double doubleValue) { System.out.printf("%nCalled square with double argument: %f%n", doubleValue); return doubleValue * doubleValue } } Called square with int argument: 7 Square of integer 7 is 49 Called square with double argument: Square of double 7.5 is
Distinguishing Between Overloaded Methods The compiler distinguishes overloaded methods by their signatures a combination of the method’s name and the number, types and order of its parameters, but not its return type. If the compiler looked only at method names during compilation, the code would be ambiguous and the compiler would not know how to distinguish between the two square methods The compiler uses longer method names that include the original method name, the types of each parameter and the exact order of the parameters to determine whether the methods in a class are unique in that class. The compiler might use the logical name “square of int” for the square method that specifies an int parameter and “square of double” for the square method that specifies a double parameter
Distinguishing Between Overloaded Methods If method1’s declaration begins as void method1(int a, float b) then the compiler might use the logical name “method1 of int and float.” If the parameters are specified as void method1(float a, int b) then the compiler might use the logical name “method1 of float and int.” The order of the parameter types is important—the compiler considers the two method1 headers to be distinct.
Return Types of Overloaded Methods Method calls cannot be distinguished only by return type. If you had overloaded methods that differed only by their return types and you called one of the methods in a statement square(2); the compiler would not be able to determine the version of the method to call, because the return value is ignored. When two methods have the same signature and different return types, the compiler issues an error message indicating that the method is already defined in the class. Overloaded methods can have different return types if the methods have different parameter lists.
class MyClass { int height; MyClass() { System.out.println("bricks"); height = 0; } MyClass (int i) { System.out.println("Building new House that is " + i + " meter tall"); height = i; } void info() { System.out.println("House is " + height + "meter tall"); } void info(String s) { System.out.println(s + ": House is " + height + " meter tall"); } } public class MainClass { public static void main(String[] args) { MyClass t = new MyClass(0); t.info(); t.info("overloaded method"); //Overloaded constructor: new MyClass(); } Building new House that is 0 metertall. House is 0 meter tall. Overloaded method: House is 0 meter tall. bricks
Invalid Examples of Method Overloading //compiler error - can't overload based on the type returned //(one method returns int, the other returns a float): int changeDate(int Year) ; float changeDate (int Year); //compiler error - can't overload by changing just //the name of the parameter (from Year to Month): int changeDate(int Year); int changeDate(int Month) ;
Valid Examples of Method Overloading //valid case of overloading, //the methods have different number of parameters: int changeDate(int Year, int Month) ; int changeDate(int Year); // valid case of overloading the parameters are of different types: int changeDate(float Year) ; int changeDate(int Year);
Overriding is Different from Overloading If a derived class requires a different definition for an inherited method, then that method can be redefined in the derived class. This is considered as overriding. An overridden method would have the exact same method name, return type, number of parameters, and types of parameters as the method in the parent class, The only difference of an overriden method would be the definition of the method
Overriding Example public class Parent { public int someMethod() { return 2; } } public class Child extends Parent{ // this is method overriding: public int someMethod() { return 4; } } Overriding happens at run time
Arrays Array objects are data structures consisting of related data items of the same type. Arrays make it convenient to process related groups of values. Arrays remain the same length once they’re created.
Arrays An array is a group of variables (called elements or components) containing values that all have the same type. Arrays are objects, so they’re considered reference types. we think of an array as a reference to an array object in memory. The elements of an array can be either primitive types or reference types To refer to a particular element in an array, we specify the name of the reference to the array and the position number of the element in the array. The position number of the element is called the element’s index or subscript.
Logical Array Representation An index must be a nonnegative integer. A program can use an expression as an index. If we assume that variable a is 5 and variable b is 6, then the statement c[a + b] += 2; adds 2 to array element c[11]. An indexed array name is an array-access expression, which can be used on the left side of an assignment to place a new value into an array element
The name of the array is c. Every array object knows its own length and stores it in a length instance variable. The expression c.length returns array c’s length. Even though the length instance variable of an array is public, it cannot be changed because it’s a final variable. This array’s 12 elements are referred to as c[0], c[1], c[2],..., c[11]. The value of c[0] is -45, the value of c[1] is 6, the value of c[2] is 0, the value of c[7] is 62 the value of c[11] is 78. To calculate the sum of the values contained in the first three elements of array c and store the result in variable sum, sum = c[0] + c[1] + c[2]; To divide the value of c[6] by 2 and assign the result to the variable x, x = c[6] / 2;
Declaring and Creating Arrays Array objects occupy space in memory. Arrays are created with keyword new. To create an array object, specify the type of the array elements and the number of elements as part of an array-creation expression that uses keyword new. Such an expression returns a reference that can be stored in an array variable. The following declaration and array-creation expression create an array object containing 12 int elements and store the array’s reference in the array variable named c: int[] c = new int[12];
Declaring and Creating Arrays When an array is created, each of its elements receives a default value zero for the numeric primitive-type elements, false for boolean elements null for references. int[] c; // declare the array variable c = new int[12]; // create the array; assign to array variable The square brackets following the type indicate that c is a variable that will refer to an array the variable will store an array reference. In the assignment statement, the array variable c receives the reference to a new array of 12 int elements.
Declaring and Creating Arrays A program can create several arrays in a single declaration. String[] b = new String[100], x = new String[27]; When the type of the array and the square brackets are combined at the beginning of the declaration, all the identifiers in the declaration are array variables. variables b and x refer to String arrays. we prefer to declare only one variable per declaration. The preceding declaration is equivalent to: String[] b = new String[100]; // create array b String[] x = new String[27]; // create array x
// Initializing the elements of an array to default values public class InitArray { public static void main(String[] args) { // declare variable array and initialize it with an array object int[] array = new int[10]; // create the array object System.out.printf("%s%8s%n", "Index", "Value"); // output each array element's value for (int counter = 0; counter < array.length; counter++) System.out.printf("%5d%8d%n", counter, array[counter]); } Index Value
Using an Array Initializer int[] n = { 10, 20, 30, 40, 50 }; creates a five-element array with index values 0–4. Element n[0] is initialized to 10, n[1] is initialized to 20, and so on. When the compiler encounters an array declaration that includes an initializer list, it counts the number of initializers in the list to determine the size of the array, then sets up the appropriate new operation
public class InitArray { public static void main(String[] args) { int[] array = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; System.out.printf("%s%8s%n", "Index", "Value"); for (int counter = 0; counter < array.length; counter++) System.out.printf("%5d%8d%n", counter, array[counter]); } Index Value
Summing the Elements of an Array public class SumArray { public static void main(String[] args) { int[] array = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 }; int total = 0; // add each element's value to total for (int counter = 0; counter < array.length; counter++) total += array[counter]; System.out.printf("Total of array elements: %d%n", total); } Total of array elements: 849