+3 votes
28 views
what is the purpose of Java shadowing.can any one explain with small Java program.thank you
asked Jun 1, 2016 in Computer Science - IT by gypsiii | 28 views

1 Answer

+2 votes
Best answer

Consider the following program :

public class Main {

    /**
     * @param args the command line arguments
     */
    static int x = 10;
    
    public static void main(String[] args) {
        // TODO code application logic here
        int x;
        x = 20;
        System.out.println("x = " + x);           
        System.out.println("Shadow Value of x = " +
            Main.x);
    }

}

This simple program will help you understand what variable shadowing is ,Yes .. the value of x is shadowed or changed by successive assignment.

Outer variable value shadows the inner value

variable shadowing is when a variable is declared in a method or class has same name variable in another block or method or class

Another value shadows the value of x which might not be last assigned value.

Also we have :

  • Method Argument Shadowing
  • SuperClass field shadowing
answered Jun 1, 2016 by slow_learner
selected Jun 1, 2016 by gypsiii