Overloading References: Beginning Java Objects, Jacquie Barker; Sara Stoecklin, FSU; Object-Oriented Analysis and Design, Grady Booch; Applying UML and Patterns, Craig Larman;
10/7/2004
1
10/7/2004
2
Method Overloading
Method Overloading
• Method overloading occurs when the same name is used for more than one method. • Two methods can have the same name if their signatures are different. • A signature is the name + number of parameters and their types. (does not include return type of the method) • Return type and argument names don’t matter in determining “overloadedness” • Argument types can be same if in different order 10/7/2004
3
class Base { public void f() { System.out.println(“f()”); } public void f(int i) { System.out.println(“f(int)”); } }// end Base public class Test { public static void main(String[] args) { Base b = new Base(); b.f(); b.f(5); } }//end Test
Overloaded methods are resolved statically (at compile time) according to the method signature.
Output: f() f(int) 10/7/2004
4
Method Overloading: Example
Method Overloading
Two methods with the same name, but with different signatures. class Base { public static void f() { System.out.println(“f()”); } public static void f(int i) { System.out.println(“f(int)”); } }//end Base public class Test { public static void main(String[] args) { Base b = new Base(); b.f(); b.f(5); } }//end Test
10/7/2004
• Because overloaded methods are resolved statically, overloaded methods can be static methods
public int setTime ( int hour, int minute) { startHour = hour; startMinutes = minutes; } // end setTime
• But, if a method requires access to non-static variables of the object, then it must be non-static.
public int setTime( int hour ) { startHour = hour; startMinutes = 0; } // setTime
Note: Two methods are named setTime, but they have a different number of parameters. When you call the methods, the signature (including the number of parameters) must match. 5
10/7/2004
6
1
Method Overloading: Example public class VCR {
class VCRtest {
VCR private int startHour, startMinutes;
setTime
public static void main (String args[ ] ) { VCR sony; sony = new VCR( ); sony.setTime(6, 3); sony.setTime(8); } // end main } // end VCRtest
public void setTime( int hour, int minute){ startHour = hour; startMinutes = minute; } // end setTime
startHhour startMinutes
public void setTime( int hour ) { startHour = hour; startMinutes = 0; } // end setTime } // end VCR
startHour :
Method Overloading: Example
1
public void setTime( int hour, int minutes){ startHour = hour; startMinutes = minutes; } // end setTime public void setTime( int hour ) { startHour = hour; startMinutes = 0; } // end setTime } // end VCR
startMinutes :
1.
setTime( ) You might want to set the time on your VCR. Perhaps you wish to set both minutes and hours or just set the hours. 10/7/2004
public class VCR { // two methods setTime overloaded private int startHour, startMinutes;
7
A new VCR is created and named sony. And the memory is created.
sony
10/7/2004
startHour startMinutes
:
8
Method Overloading: Example
Method Overloading: Example
class VCRtest {
class VCRtest {
public static void main (String args[ ] ) { VCR sony; sony = new VCR( ); sony.setTime(6, 3); sony.setTime(8); } // end main } // end VCRtest
2.
public class VCR { // two methods setTime overloaded private int startHour, startMinutes;
2
The first method is called because the signature has two parameters of int type.
public static void main (String args[ ] ) { VCR sony; sony = new VCR( ); sony.setTime(6, 3); sony.setTime(8); 3 } // end main } // end VCRtest
public void setTime( int hour, int minutes){ startHour = hour; startMinutes = minutes; 2a } // end setTime public void setTime( int hour ) { startHour = hour; startMinutes = 0; } // end setTime } // end VCR
2a. The startHour is set to 6. The startMinute is set to 3.
3.
The second method is called because the signature has one parameter of int type.
public class VCR { // two methods setTime overloaded private int startHour, startMinutes; public void setTime( int hour, int minutes){ startHour = hour; startMinutes = minutes; } // end setTime public void setTime( int hour ) { startHour = hour; startMinutes = 0; } // end setTime } // end VCR
3a
3a. The startHour is set to 8.
sony
startHour 6 startMinutes : 3
10/7/2004
sony 9
Method Overloading: Example Several methods with different types of parameters
10/7/2004
startHour : startMinutes :
8 0 10
class Base { public void f( ) { System.out.println("Base::f( )"); }//end f }//end Base
Method Overloading
• Remember the method “out” in System that prints on the console. • It has several overloaded methods.
class Derived extendsBase { public void f (int i) { System.out.println("Derived::f (int)"); }//end f }//end Derived
public void println(int n) { * * }// end println
public class Test 2{ public static void main(String[] args) { Derived d = new Derived(); d.f ( ); }//end main }//end Test2
public void println(float n) { *
*
}// end println public void println(double n) {
A class may inherit a method that overloads an existing method.
Output
* * Base::f( )
}// end println 10/7/2004
11
10/7/2004
12
2
Method Overloading - Constructors
Method Overloading
BankAccount
class BankAccount { private double balance; private boolean atmCard;
public class OutputTest { // printing an integer, float, or double
$ java OutputTest
int a = 4; float f2 = 56.94f; double d3 = 67.89;
The BankAccount class has two constructors with different signatures Constructor one has 0 parameters Constructor two has one double parameter. Constructor three has three parameters, one double and one boolean.
System.out.print(“Here is an integer : “); System.out.println(a); System.out.print(“Here is a float: “); System.out.println(f2);
Line One: the print method printed an integer Line Two: it printed a float Line Three: it printed a double.
System.out.print(“Here is a double: “); System.out.println(d3); } // end main }// end OutputYest
10/7/2004
BankAccount checking1,checking2; double amount;
public BankAccount( ) { balance = 0; atmCard = true; }// end constructor
checking1 = new BankAccount( ); 2 checking2 = new BankAccount( 123.98 , false); amount = Double. parseDouble(a[0] ); checking1.deposit( amount ); System.out..print(“Amount to deposit in acct 2? “); amount = Double.parseDouble (a[1] ); checking2.deposit( amount ); }// end main }// end BankTest
1.
Two new BankAccounts are created and named checking1 and checking2 respectively. The memory is created for both the two variables.
2.
}// end BankAccount
class BankAccount { private double balance; private boolean atmCard;
public class BankTest { public static void main(String a [ ] ) {
2a
BankAccount checking1,checking2; double amount;
1
2 checking1 = new BankAccount( ); checking2 = new BankAccount( 123.98 , false); amount = Double. parseDouble(a[0] ); checking1.deposit( amount ); System.out..print(“Amount to deposit in acct 2? “); amount = Double.parseDouble (a[1] ); checking2.deposit( amount ); }// end main }// end BankTest
public BankAccount(double initialDeposit) { balance = initialDeposit; atmCard = true; }// end constructor public BankAccount (double initialDeposit, boolean atm) { balance = 0; atmCard = atm; }// end construcor public void deposit (double dollarAmount ) { balance = balance + dollarAmount; }// end deposit }// end BankAccount
10/7/2004
14
Method Overloading - Constructors
class BankAccount { private double balance; private boolean atmCard;
1
public BankAccount (double initialDeposit, boolean atm) { balance = 0; atmCard = atm; } // end constructor
10/7/2004
Method Overloading - Constructors public static void main(String a [ ] ) {
public BankAccount (double initialDeposit) { balance = initialDeposit; atmCard = true; }// end constructor
public void deposit (double dollarAmount ) { balance = balance + dollarAmount; } // end deposit 13
public class BankTest {
public BankAccount( ) { balance = 0; atmCard = true; }// end BankAccount
Constructor Methods can also be overloaded.
public static void main(String args [ ] ) {
Here is an integer: 4 Here is a float: 56.9 Here is a double: 67.89
1. 2a.
15
A new BankAccount is created named checking1. The first constructor is called since there are no parameters.
10/7/2004
public BankAccount( ) { balance = 0; atmCard = true; }// end constructor
2a
public BankAccount(double initialDeposit) { balance = initialDeposit; atmCard = true; }// end constructor public BankAccount (double initialDeposit, boolean atm) { balance = 0; atmCard = atm; }// end construcor public void deposit (double dollarAmount ) { balance = balance + dollarAmount; }// end deposit }// end BankAccount 16
Method Overloading - Constructors public class BankTest { public static void main(String a [ ] ) {
class BankAccount { private double balance; private boolean atmCard; public BankAccount( ) { balance = 0; atmCard = true; }// end constructor
BankAccount checking1,checking2; double amount; checking1 = new BankAccount( ); 3 checking2 = new BankAccount( 123.98 ); amount = Double. parseDouble(a[0] ); checking1.deposit( amount ); System.out.print(“Amount to deposit in acct 2? “); amount = Double.parseDouble (a[1] ); checking2.deposit( amount ); }// end main }// end BankTest 3. 3a.
A new BankAccount is created named checking2. The second constructor is called since there are two parameters of type double and boolean.
10/7/2004
Overriding
3a public BankAccount(double initialDeposit) { balance = initialDeposit; atmCard = true; }// end constructor public BankAccount (double initialDeposit, boolean atm) { balance = 0; atmCard = atm; }// end construcor public void deposit (double dollarAmount ) { balance = balance + dollarAmount; }// end deposit }// end BankAccount 17
10/7/2004
18
3
Overriding
Overriding
• We’ve seen that inheritance allows a new class to reuse implementation from another class. Inheritance makes code automatically available as part of the new class. • When you program with implementation inheritance, you are stuck with whatever implementation you inherit. • However, an inheriting class can override the protected methods in order to alter the implementation. • Overriding can lessen the impact of inheriting a poor or inappropriate implementation.
• Overriding occurs when you have two methods, both with the same signature, and one is a method in a subclass of the other class containing the same signature method. • Sometimes called “shadowing.” • Subclasses give new behavior to methods • Famous override: toString()
10/7/2004
10/7/2004
19
Overriding Example class Student { protected String name; protected String studentID; protected double gpa; … void print() { System.out.println(“Name :” + name + “\nID: “ + studentID + “GPA: “ + gpa); }//end print }//end Student
Overriding
class GraduateStudent extends Student { String undergradDegree; String undergradInstitution; … void print() { System.out.println(“Name : “ + “\nID: “ + studentID + “GPA: “ + gpa + “Undergrad Deg: “ + undergradDegree + “\nUndergrad Inst: “ + undergradInstitution); }//end print }//end GraduateStudent
10/7/2004
21
• The previous example has duplicate code in the overriding print method that should be eliminated. We can do this by having the GraduateStudent print method call the print method for the Student class and then print the additional features of the grad student.
10/7/2004
Overriding public class TV { protected boolean on; protected int channel; public void turnOn( ) { on = true; channel = 2; } // end turnOn public void turnOff( ) { on = false; }// end turnOff public void changeChannel (int newchannel ) { channel = newchannel; } // end changeChannel public void displayChannel ( ) { if( on == true) System.out.println(channel); } // end changeChannel }10/7/2004 // end TV
20
class GraduateStudent extends Student { String undergradDegree; String undergradInstitution; … void print() { super.print(); System.out. println() { ‘Undergrad Deg: “ + undergradDegree + “ \nUndergrad Inst: “ + undergradInstitution); }//end print 22 }//end GraduateStudent
Overriding
public class MyTV extends TV { public void displayChannel( ) { if( on == true) System.out.println(“******”); System.out.println(“ “ + channel); System.out.println(“******”); } // end displayChannel } // end MyTV
Note: The class MyTV which extends the original TV class has a method displayChannel which overrides the display Channel in TV. When we use an instance of MyTV it will use its method. When we use an instance of TV it will use its method. 23
•
In a complex inheritance hierarchy, any class not specifically implementing/ overriding a specific method signature itself will inherit the definition of that method from its most immediate ancestor.
D (Undergrad)
A (Person) print()
B (Student) print()
E (Graduate) print()
C (Professor)
F (continuing)
Classes A,B and E use their own print methods, individually defined for them. Class C inherits the print method from class A and Classes D&F inherit their print methods from B. No overriding 10/7/2004 in C, D or F. 24 occurs
4
Overriding • Subclasses give new behavior to methods • Famous override: toString • Can specialize by doing stuff and still calling the superclass method
10/7/2004
25
5