The overloading mechanism in Java implements parameter polymorphism, allowing methods with the same name to handle different types of parameters. Overloaded methods are matched based on parameter types, with the following priority: exact match types, auto-conversion types, and relaxed match types. In the practical case, overloaded methods for calculating the area of rectangles and circles are provided, demonstrating how to call appropriate methods based on different shape inputs.
In Java, overloading allows parameters with the same name to be defined in the same class Different multiple methods. This provides a way to use the same function name to handle different types or numbers of arguments.
The syntax for overloaded methods is as follows:
methodName(parameter1_type parameter1_name, parameter2_type parameter2_name, ...)
The following example demonstrates two overloaded calculate
methods:
public class MyClass { public int calculate(int num1, int num2) { return num1 + num2; } public double calculate(double num1, double num2) { return num1 * num2; } }
When an overloaded method is called, Java will match the parameters to the appropriate method based on the following rules:
The following is a practical case that demonstrates how to use overloading methods to handle different types and numbers of parameters:
import java.util.Scanner; public class AreaCalculator { public double calculateArea(int length, int width) { return length * width; } public double calculateArea(int radius) { return Math.PI * radius * radius; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter shape (rectangle/circle): "); String shape = scanner.nextLine(); if (shape.equals("rectangle")) { System.out.print("Enter length: "); int length = scanner.nextInt(); System.out.print("Enter width: "); int width = scanner.nextInt(); AreaCalculator calculator = new AreaCalculator(); double area = calculator.calculateArea(length, width); System.out.println("Area of rectangle: " + area); } else if (shape.equals("circle")) { System.out.print("Enter radius: "); int radius = scanner.nextInt(); AreaCalculator calculator = new AreaCalculator(); double area = calculator.calculateArea(radius); System.out.println("Area of circle: " + area); } else { System.out.println("Invalid shape"); } } }
The above is the detailed content of How is the overloading mechanism in Java functions implemented for different parameters?. For more information, please follow other related articles on the PHP Chinese website!