Method Overloading

Method Overloading in Java

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:

  • Methods must have the same name.
  • Methods must have a different number or type of parameters.
  • The return type can be different, but it does not play a role in method overloading.

Example scenarios:

  • Overloading constructors with different parameter lists.
  • Having multiple print methods that accept different data types.
Example
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);
    }
}

Java Scope

What is scope in Java?

Scope refers to the region of a program where a variable is accessible. Java has three main types of scope:

  • Local Scope: Variables declared within a method or block.
  • Instance Scope: Variables declared within a class but outside any method; they belong to instances (objects) of the class.
  • Class Scope (Static Scope): Variables declared as static within a class; they belong to the class itself.

Variable visibility and lifetime:

  • Local variables have limited scope and exist only within the block or method where they are declared.
  • Instance variables have instance scope and are specific to objects of the class.
  • Class variables (static) have class scope and are shared among all instances of the class.
Java Scope Example:
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();
    }
}

Contact Us

Name
Email
Mobile No:
subject:
Message: