
Tutorial Questions Semester 1, 2020
Tutorial 7 Solutions
You will be expected to engage with the tutor and discuss solutions to the problems below.
1. Explain why a static method cannot refer to an instance variable.
Solution:
Static methods may be called without instantiating an object. Therefore, an instance variable may not
have an assigned value when a static method is called, so a static method cannot reference it.
2. Explain why method overloading is useful.
Solution:
Method overloading is useful because it allows multiple methods to have the same name as long as they
have different signatures (method name and parameter list [types, number, order]). This allows for more
flexibility in choosing identifiers for methods, since the alternative would require the programmer to have
different method identifiers for every method that took in a different set of parameters.
3. Method Overloading
i. Write a method called average that accepts two integer parameters and returns their
average as a floating point value.
Solution:
pu b li c do u bl e av e ra g e ( i nt nu m1 , i nt nu m 2 ) {
re tu rn ( n um 1 + num2 ) / 2.0;
}
ii. Overload the average method of Exercise 3.i such that if three integers are provided as
parameters, the method returns the average of all three.
Solution:
pu bl ic do ub le av er ag e ( in t nu m1 , i nt n um2 , in t n um3 ) {
re tu rn ( n um 1 + num2 + nu m3 ) / 3. 0;
}
iii. Overload the average method of Exercise 3.i to accept four integer parameters and
return their average.
Solution:
pu bl ic do ub le av er ag e ( in t nu m1 , i nt n um2 , in t nu m3 , i nt nu m4 ) {
re tu rn ( n um 1 + num2 + nu m3 + n um 4 ) / 4.0 ;
}
iv. Write a method called multiConcat that takes a string parameter called text and an
integer parameter called count. Return a string that consists of text concatenated with
itself count times. For example, if the parameter values are "hi" and 4, the return
value is "hihihihi". Return the original string if the integer parameter is less than 2.
COMP1102/8702 Computer Programming 1, CHM & LJS
College of Science & Engineering, Flinders University
34