Method overloading is a feature in Java that allows you to define multiple methods in the same class with the same name but different parameter lists. Java determines which method to call based on the number and types of arguments provided.
Rules for method overloading:
Example scenarios:
public class Calculator { public int add(int a, int b) { return a + b; } public double add(double a, double b) { return a + b; } public static void main(String[] args) { Calculator calc = new Calculator(); int sumInt = calc.add(5, 3); double sumDouble = calc.add(2.5, 3.7); System.out.println("Sum of integers: " + sumInt); System.out.println("Sum of doubles: " + sumDouble); } }
Scope refers to the region of a program where a variable is accessible. Java has three main types of scope:
Variable visibility and lifetime:
public class ScopeExample { // Instance variable private int instanceVar = 10; public void exampleMethod() { // Local variable int localVar = 5; System.out.println("Local variable: " + localVar); System.out.println("Instance variable: " + instanceVar); } public static void main(String[] args) { ScopeExample obj = new ScopeExample(); obj.exampleMethod(); } }