KnowledgeBoat Logo
|

Computer Applications

What is meant by scope of variables? Show its application with the help of an example.

Encapsulation & Inheritance in Java

9 Likes

Answer

Scope of variables refers to the extent of their usage in a program. Basically, a variable is used within the block in which it is declared. Based on the scope of usage, the variables can be categorised into three types:

  1. Instance Variables — The member variables that store the state of an object are known as instance variables.
  2. Class Variables (static variable) — A variable declared in a class with the static modifier is called a class variable.
  3. Local Variables — The variables declared inside a method or block are called local variables. The scope of local variables is limited to the method or the block they are declared in.

Consider the example given below:

class Scope {
    String name;
    static int companyname;
    double sal, extra; 
    Scope(String n, double x, double y) {
        companyname = "HCL";
        name = n;
        sal = x;
        extra = y;
    }
    void calculate()  {
        double total = sal + extra;
    }
    void disp() {
        System.out.println(name + " " + companyname);
        System.out.println("Salary = " + total);
    }
}

Let the objects of class Scope be created as:
Scope ob1 = new Scope("Amit Kumar", 30000.0 , 3500.0);
Scope ob2 = new Scope("Suraj Jain", 25000.0 , 2000);

Here, name, sal and extra are instance variables which will be accessible throughout the class and have different values for different objects.
Variable companyname is class variable and has the same value for each object of the class.
Variable total is a local variable of calculate(). It can be used only within the function and will generate an error — "Variable not found" when we try to access it in disp().

Answered By

5 Likes


Related Questions