Show Mobile Navigation

Webring

Powered by WebRing.
,

Variable Shadowing with example, in Java?

Sachin R Kukale - 02:18

In this section we will focus our attention on one more important very tricky concept of variable
shadowing in java.
So what is variable shadowing?
So when we have some variables declared in super class and due to access modifier attached to that
variable it is not visible in child class. So in this case we can create the same variable with same
same name and value in child (because it is not visible in child class whenever the code in child
class is running compiler cannot access the variables restricted for visibility) and we can use that
variable with same name for totally different purpose.

public class VariableShadowing{

private int a=77;
//Private variable hence cannot be accessed outside the class in any way.
int b=88;
//Instance variable.

public VariableShadowing(){

System.out.println("The original variable 'a' from VariableShadowing class:\n");

System.out.println(a);

}

public static void main(String[] args){

Bingo b=new Bingo();
/*Here I have created the instace of only child class so
It will automatically call the constructor from parent class
and it will avoid the printing of result twice from parent class
constructor*/

}

}

class Bingo extends VariableShadowing{

int a=55;

public Bingo(){
/*Here 'a' is instance variable. Though the class Bingo extends class VariableShadowing the private instance variable 'a' of VariableShadowing is not visible and so we can declare, initialize and use the variable with same name i.e.'a'.*/

System.out.println("The shadowed variable 'a' from Bingo class:");

System.out.println(a);

}

}

0 comments:

Post a Comment