Page 384 - Computer_Science_F5
P. 384
// Method to multiply a double and an integer
public double multiply(double a, int b) {
return a * b;
} Chapter Five: Object oriented programming with Java
FOR ONLINE READING ONLY
public static void main(String[] args) {
ArithmeticOperations arithmetic = new ArithmeticOperations();
// Method overloading for addition
System.out.println(“Sum of 150 and 12: “ + arithmetic.add(150, 12));
System.out.println(“Sum of 11, 12, and 23: “ + arithmetic.add(11,12,23));
System.out.println(“Sum of 7.5 and 9.3: “ + arithmetic.add(7.5, 9.3));
System.out.println(“Concatenated string: “ + arithmetic.add(“Habari rafiki”,
“Tanzania”));
// Method overloading for multiplication
System.out.println(“Product of 11 and 22: “ + arithmetic.multiply(11, 22));
System.out.println(“Product of 10.2 and 8: “ + arithmetic.multiply(10.2, 8));
}
}
Output:
In this program, there are several variations of the add and multiply methods,
each with different types of parameters. When these methods are called, Java
determines the correct method to execute based on the number and types of
arguments provided. This illustrates method overloading, which is a type of
compile-time polymorphism.
Exercise 5.8 3. Explain the concept of method
overloading in Java. How does it
1. Define polymorphism in Java and
explain how it contributes to the enable polymorphism? Provide a
flexibility and extensibility of scenario where method overloading
object-oriented programs. would be useful.
2. Describe the two types of 4. Discuss the significance of method
polymorphism in Java: compile- overriding in Java polymorphism.
time (method overloading) and How does it allow subclasses to
runtime (method overriding). provide their own implementation
Provide examples of each. of inherited methods?
375
Student’s Book Form Five
Computer Science Form 5.indd 375 23/07/2024 12:34

