← कोर्स पर वापस जाएँ: Java from scratch

Overloading, variable scope and static

वीडियो जल्द आ रहा है

With what you already know you can write useful methods. In this lesson we will see three ideas that make them more convenient and that will appear constantly in any Java code: overloading (several methods with the same name), variable scope (where each one exists) and the static keyword, which prepares the ground for understanding classes in week 6. You will also meet variable arguments, which let you pass an indefinite number of values.

Method overloading

Java lets you define several methods with the same name as long as their parameter list is different, either in number or in types. That is what happens with System.out.println, which accepts text, integers, decimals and more. When calling, the compiler picks the version whose parameters best match the arguments. Keep in mind that the return type does not count: two methods that differ only in what they return cannot coexist, because the compiler would not know which to choose.

java
public class Main {
    static int area(int side) {                  // square
        return side * side;
    }

    static int area(int width, int height) {     // rectangle
        return width * height;
    }

    static double area(double radius) {          // circle
        return Math.PI * radius * radius;
    }

    // Varargs: any number of ints, received as an array
    static int sum(int... numbers) {
        int total = 0;
        for (int n : numbers) total += n;
        return total;
    }

    static String describe(String label, int... values) {
        return label + ": " + values.length + " values, sum " + sum(values);
    }

    public static void main(String[] args) {
        System.out.println(area(4));                 // 16
        System.out.println(area(3, 5));              // 15
        System.out.printf("%.2f%n", area(2.0));      // 12.57
        System.out.println(sum());                   // 0
        System.out.println(sum(1, 2, 3, 4));         // 10
        System.out.println(describe("data", 5, 10)); // data: 2 values, sum 15
    }
}

Variable scope

The scope of a variable is the area of the code where you can use it. A local variable exists from where it is declared until the end of the brace block where it sits. The variables of a method are not visible from other methods; parameters live as long as the call lasts. A variable declared inside a for exists only inside that for. You cannot declare two variables with the same name in nested blocks of the same method, but you can in separate blocks. This rule prevents you from changing by accident a variable that was not the one you thought.

static: class fields and constants

A field declared outside the methods but inside the class, with the static keyword, belongs to the whole class and not to a method: all methods share it and it keeps its value between calls. Combined with final it serves for constants such as TAX_RATE. Methods marked static can be called without creating any object, which is why main and the helper methods we have written are static. Abusing mutable static fields is bad practice, because any part of the program can change them and the state becomes hard to follow; use them sparingly.

java
public class Main {
    static final double TAX_RATE = 0.21;     // constant shared by all methods
    static int callCount = 0;                // shared mutable state

    static double withTax(double price) {
        callCount++;
        return price * (1 + TAX_RATE);
    }

    static void scopeDemo() {
        int x = 10;                          // local to scopeDemo
        for (int i = 0; i < 2; i++) {
            int temp = i * x;                // exists only inside this loop body
            System.out.println("temp = " + temp);
        }
        // System.out.println(i);            // error: i is out of scope
        // System.out.println(temp);         // error: temp is out of scope
    }

    public static void main(String[] args) {
        System.out.printf("%.2f%n", withTax(100));   // 121.00
        System.out.printf("%.2f%n", withTax(50));    // 60.50
        System.out.println("Calls: " + callCount);   // 2
        scopeDemo();
        System.out.println(Math.max(3, 9));          // static method of another class
    }
}

जो सीखा उसे परखें

प्रश्न 1 / 1

What must differ between two overloaded methods?

✎ मेरे नोट्स

केवल इस ब्राउज़र में सहेजा गया। खाते में रखने के लिए साइन इन करें।0/5000 अक्षर

← पिछलाअगला →