variable scope in java | java variable scope

variable scope in java | java variable scope

 

variable scope in java

Variable scope in java

The Scope of a variable refers to its visibility. Sometimes, a method needs to refer to the object we are currently using. Java added the reserved word ‘this’ for this task.

‘this’ is an operator that allows us to access the current object (the class being used), and among other things, it will help us access the properties or methods of the class. Using "this", we can make the parameters received in the method different from the properties of the class.

 public class WithThis

{

    int x, y;

    // Parameterized constructor

    WithThis(int x, int y)

    {

        this.x = x;

        this.y = y;

    }

    void display()

    {

        //Displaying value of variables a and b

        System.out.println("x = " + x + "  y = " + y);

    }

    public static void main(String[] args)

    {

        WithThis ob = new WithThis(40, 60);

        ob.display();

    }

}

As you can see from the code above, we have a code whose properties are named x and y, and the constructor of this class also receives two parameters called x and y. In order to make these two variables (the attributes of the class and the parameters received in the method) different, we can use the word "this" as follows:

We use the operator this

WithThis (int x, int y)

{

this.x = x;

this.y = y;

}

 As we can see, to make a difference between the values received in the Constructor and the attributes of the class, we can use the ‘this’ operator.

This is just an example of using the "this" operator, but basically it allows us to access the properties and methods of the current object being used. First of all, this can be confusing because we are using the code of the class (ie the template) and this code will only be executed before the object is created and this constructor is called​​. We send parameters, and the constructor receives and processes them. Therefore, we must be accustomed to thinking about two moments, namely creating a class or template and creating an object, which will happen when the code we programmed in the class or template is actually executed.

Although the use of the 'this' operator will sometimes seem redundant, it is a good practice to use it to refer to the attributes of the class in which we are working, since by reading our code we will quickly recognize which variables are attributes of a class and which are not. They are. Within the constructors or methods of a class, the ‘this’ operator will always reference the object that was invoked. If we look at the code, both the received argument and the class attribute are called exactly the same, so the argument about the class attribute takes precedence, this is known as concealment of the class attribute. And to solve this problem, it is enough to use the ‘this’ operator before the variable, just as if we were accessing the attribute of a class by means of the dot operator.

Depending on where the variable is defined, it will be the duration of the variable, and this is known as the Scope of a Variable. If we define a variable as an attribute of a class, this variable is known as a Class variable, and it will exist for as long as the object exists in memory.

These variables will automatically be initialized with their default values. For example, the value of integer type will be initialized to 0, the variable type of Boolean type will be initialized to false, and the Object type of Boolean value will be initialized to null. On the other hand, local variables are any variables defined in the method, including the parameters received by the function.

These variables will automatically be initialized with their default values. For example, the value of integer type will be initialized to 0, the variable type of Boolean type will be initialized to false, and the Object type of Boolean value will be initialized to null. On the other hand, local variables are any variables defined in the method, including the parameters received by the function.

More Java program

Super keyword in java

Super keyword in java

 

Super keyword in java

Super keyword in java with Example

The super keyword is a reference variable which refers to its parent class, which means inheritance must be there. Same as this keyword in java, which refers to the same class object. We can say that whenever the base class version of the method is called which is overridden in the child class. Here super can access the immediate parent class method and variables.


For example, consider the following program

class Parent

{

     void display()

      {

                System.out.println (“I am from parent class”);

      }

}

class Child extends Parent

{

       void display()

      {

                display();     // it lead to recursion

                System.out.println (“I am from Child class”);

      }

}

When we display() method in child class lead to recursion.

public class RunPrg

{

    public static void main(String args[])

    {

        Child ob=new Child();

        ob.display ();

    }

}

To avoid recursion we need a super keyword for calling the parent class method. In the following child class version, we used the super in display() method.

public class Child extends Parent

{

    void display()

      {

        super.display();   // use of super to call the parent class method

                System.out.println ("I am from Child class");

      }

}

the super keyword can be used to refer parent class instance variable.

The instance variable of the parent class can be accessed in the child class with the help of the super keyword.

public class Parent

{   

    String team="KKR";    

}

After the parent class, we define the child class, which calls the parent class instance variable with the super keyword.

public class Child extends Parent

{

    String team="RCB";

    void display()

      {

        System.out.println ("Team of Parent=" + super.team);

                System.out.println ("Team of Child =" + team);

      }

}

We need to run the child with RunPrg class where the main() method defined.

public class RunPrg

{

    public static void main(String args[])

    {

        Child ob=new Child();

        ob.display();

    }

}

Output

Team of Parent=KKR

Team of Child =RCB

 

the super keyword can be used to refer parent class constructor

with the help of the super keyword, we can access the parent class constructor as follows

public class Parent

{   

    Parent()

    {

        System.out.println("I am parent class constructor");

    }

}

Note: Call to super() must be first the statement in the child (drive) Class constructor.

Below is a child class example

public class Child extends Parent

{

    Child()

    {

        super(); // called the parent class constructor

        System.out.println("I am Child class constructor");

    }

}

And then run the program with another class as follows

public class RunPrg

{

    public static void main(String args[])

    {

        Child ob=new Child();       

    }

}

Output will as

I am parent class constructor

I am Child class constructor


More Java program

this keyword in java - , this reference in Java

this keyword in java - , this reference in Java

this keyword in java

‘this’ is a reference variable that refers to the current object. It is a keyword in java language which represents a current object.

The ‘this’ keyword in java solve the confusion when there are the same instance variable and local variable.

With the help of this keyword, we can access current class methods or function, instance variable, and constructors of the same class within the class.

The ‘this’ can only be used inside the class and cannot be used outside the class. The ‘this’ reference is a constant reference.

Usage of ‘this’ reference is as follows:

  • ‘this’ keyword is used to refer to the current instance variable
  • ‘this’ implicitly reference used by the system
  • ‘this’ used as a method argument
  • ‘this’ invoke a constructor 
  • ‘this’ returns the current class instance
  • ‘this’ used as an argument in the constructor call

'this' Keyword in Java with Example

this’ keyword is used to refer to the current instance variable

 public class Summation

{

    int a, b, c;

    void sum(int a, int b)

    {

        a=a;

        b=b;      

    }

    void display()

    {

        System.out.println("a=" + a);

        System.out.println("b=" + b);

    }

    public static void main(String args[])

    {

        Summation ob=new Summation();

        ob.sum(30, 40);

        ob.display();

    }

}

Output

a=0

b=0

Reason: In the above method sum, the arguments are declared as a and b, and the instance variables are also named as a and b.

void sum(int a, int b)

 {

      a=a;

      b=b;      

 }

During compilation compiler get confused and fail to differentiate between instance variable and local variable (argument) , so it assign 0 to a and b

Solution to this confusion is java this keyword.

public class Summation

{

    int a, b, c;

    void sum(int a, int b)

    {

        this.a=a;                        // this keyword used

        this.b=b;           // this keyword used

    }

    void display()

    {

        System.out.println("a="+a);

        System.out.println("b="+b);

    }

    public static void main(String args[])

    {

        Summation ob=new Summation();

        ob.sum(30,40);

        ob.display();

    }

}

After providing ‘this’ this.a=a and this.b=b

Compiler become aware that the left side is the instance variable and right side local variable (formal argument) and the output as

a=30

b=40


‘this’ used as a method argument

this can be passed as an argument to a method in a class. It is used to represent an object of that class.

It will clear with the following example

class MethodArgument

{

  void firstMethod(MethodArgument obj) // Object as an argument

  {

    System.out.println ("This is method call");

  }

  void secondMethod()

  {

    firstMethod (this);

  }

}

In the above class object passed as an argument. And in the following class called with the help of MethodArgument class

public class MethodCall

{

   public static void main(String args[])

   {

       MethodArgument ob=new MethodArgument();

       ob.secondMethod();

    }

}


‘this’ invoke a constructor

 The this() keyword can be used to invoke the current class constructor. It is used as constructor chaining.

public class Constructor

{

    Constructor()

    {

        System.out.println("I am inside Constructor class");

    }

    Constructor(int x)

    {

        this();

        System.out.println(x);

    }

}

In the above class a default constructor called within a parameterized constructor with the help of this.

Note: It should be kept in mind that this should be the first statement in the other constructor.

public class CallConstructor

{

    public static void main(String args[])

    {

        Constructor ob=new Constructor(200);       

    }

}


this can be used to return the current class instance

public class AreaSquare

{

    int s, area;

    AreaSquare(int side)

    {

        s = side;

       area = s*s;

    }

    void areaSquare()

    {

       area = s*s;

       System.out.println("Area of Square:" + area);

       System.out.println("Calling method");

    }

    AreaSquare getObj()

    {

        return this;

    }

}

In the above program, this is used return. The return must be class other return will not work. For running or calling the areaSquare() method we have to take the reference as

new AreaSquare(10).getObj().areaSquare();       

public class CallAreaSquare

{

    public static void main(String args[])

    {       

        System.out.println("Calling method");

        new AreaSquare(10).getObj().areaSquare();       

    }

}

Output

Calling method

Area of Square:100

Inside method

More Java program