J.E.D.I
10.6 Overloading Methods
In our classes, we want to sometimes create methods that has the same names but function differently depending on the parameters that are passed to them. This capability
is possible in Java, and it is called Method Overloading.
Method overloading allows a method with the same name but different parameters, to have different implementations and return values of different types. Rather than invent
new names all the time, method overloading can be used when the same operation has different implementations.
For example, in our StudentRecord class we want to have a method that prints information about the student. However, we want the print method to print things
differently depending on the parameters we pass to it. For example, when we pass a String, we want the print method to print out the name, address and age of the student.
When we pass 3 double values, we want the method to print the students name and grades.
We have the following overloaded methods inside our StudentRecord class,
public void print String temp {
System.out.printlnName: + name; System.out.printlnAddress: + address;
System.out.printlnAge: + age; }
public void printdouble eGrade, double mGrade, double sGrade
System.out.printlnName: + name; System.out.printlnMath Grade: + mGrade;
System.out.printlnEnglish Grade: + eGrade; System.out.printlnScience Grade: + sGrade;
}
Introduction to Programming I 159
J.E.D.I
When we try to call this in the following main method, public static void main String[] args
{ StudentRecord
annaRecord = new StudentRecord; annaRecord.setNameAnna;
annaRecord.setAddressPhilippines; annaRecord.setAge15;
annaRecord.setMathGrade80; annaRecord.setEnglishGrade95.5;
annaRecord.setScienceGrade100;
overloaded methods annaRecord.print annaRecord.getName ;
annaRecord.print annaRecord.getEnglishGrade, annaRecord.getMathGrade,
annaRecord.getScienceGrade; }
we will have the output for the first call to print, Name:Anna
Address:Philippines Age:15
we will have the output for the second call to print, Name:Anna
Math Grade:80.0 English Grade:95.5
Science Grade:100.0
Always remember that overloaded methods have the following properties, – the same name
– different parameters – return types can be different or the same
Introduction to Programming I 160
J.E.D.I
10.7 Declaring Constructors