Skip to main content

What is variable hiding and shadowing?

In Java, there are three kinds of variables: local variables, instance variables, and class variables. Variables have their scopes. Different kinds of variables have different scopes. A variable is shadowed if there is another variable with the same name that is closer in scope. In other words, referring to the variable by name will use the one closest in scope , the one in the outer scope is shadowed.

A Local Variable Shadows An Instance Variable


Inside a class method, when a local variable have the same name as one of the instance variable, the local variable shadows the instance variable inside the method block.
In the following example, there is a instance variable named "a", and inside the method setA() there is a local variable "a":
class Program {
  int  a;
  int  b;

  void setA(int a) {
    a = a; //here, the local variable has closer scope than the instance 
          // variable, so the expression set parameter equal to itself
    this.a = a; // this is the correct way to set the parameter to the 
           //instance variable.
  }

  void setB(int b) {
    this.b = b;
  }
}
Let's look at another example,
class Program {
   String name = "Instance Var."; 
   void someMethod() { 
     String name ="Local Var."; 
     System.out.println(name);   //Local Var.
     System.out.println(this.name); //Instance Var. 
   } 
}
Note: Instance variables are not overridden, they are hidden.

A Class Variable Shadows the Inherited Variable from Its Parent Classes


When an instance variable in a subclass has the same name as an instance variable in a super class, then the instance variable is chosen in the class that is the reference type.
A class can declare a variable with the same name as an inherited variable from its parent class, thus "hiding" or shadowing the inherited version. (This is like overriding, but for variables.) For example,
public class Base {
    public  String name = "Base";
    public  String getName() { return name; }
}


public class Sub extends Base {
    public String name = "Sub";
    public String getName() { return name; }
}
The above shows two classes and Sub class is a subclass of Base class. Both of classes has a String type variable named name.
  • Use Case I

    class Program {
      public static void main(String[] args) {
        Sub s = new Sub();
        System.out.println(s.name); //Output "Sub"
      }
    }
    The above code directly accesses the name variable in the instance of Sub named s. This access, as one would expect, yields a value of "Sub".
  • Use Case II

    class Program {
      public static void main(String[] args) {
        Sub s  = new Sub();
        Base b = s;
        System.out.println(s.name); //Output "Sub"
        System.out.println(b.name); //Output "Base"
      }
    }
    In use case II, even though the variable b refers an instance of class Sub, the b.name still evaluates to "Base". Because variables names in Java are resolved by the reference type, not the object they are referencing.
    In this example, even though both b and s are referencing the object of type Sub, s is declared as type Sub, b is declared as type Base, Java runtime gets the s.name from the class of Sub, and b.name from the class of Base.

Access Supper Class Variables


When shadowing does happen, you can access the super class name by either the syntax super.name or by casting the object to its super class, with the syntax ((Superclass)object).name.
Variables shadowed by Interface hierarchies are referenced the same way they are for class hierarchies. The following example shows the shadowing from interface hierarchies:
interface IBase {
  String name = "base";
}

interface ISub extends IBase {
  String name = "sub";
}

public class Shadow implements ISub {
  String name = "shadow";

  void print(Strig name)
  {
    System.out.println("method name = " + name);
    System.out.println("class name = " + this.name);
    System.out.println("IBase name = " + 
          ((IBase) this).name);
    System.out.println("ISub name = " + 
          ((ISub) this).name);
  }

  public static void main(String[] args) {
    (new Shadow()).print("parameter");
  }
}

The output of this program is: 

method name = parameter
name = shadow
IBase name = base
ISub name = sub
As you can see, it can be confusing when variable shadowing occurs. It's a good practice not to use the same variable names in the class or interface hierarchies.
There are exceptions. When the variable in the supper class has private access or is in another package and has default access, there is no room for confusion. The sub class cannot access such variables in its supper class.

Comments

Popular posts from this blog

Advantages & Disadvantages of Synchronous / Asynchronous Communications?

  Asynchronous Communication Advantages: Requests need not be targeted to specific server. Service need not be available when request is made. No blocking, so resources could be freed.  Could use connectionless protocol Disadvantages: Response times are unpredictable. Error handling usually more complex.  Usually requires connection-oriented protocol.  Harder to design apps Synchronous Communication Advantages: Easy to program Outcome is known immediately  Error recovery easier (usually)  Better real-time response (usually) Disadvantages: Service must be up and ready. Requestor blocks, held resources are “tied up”.  Usually requires connection-oriented protocol

WebSphere MQ Interview Questions

What is MQ and what does it do? Ans. MQ stands for MESSAGE QUEUEING. WebSphere MQ allows application programs to use message queuing to participate in message-driven processing. Application programs can communicate across different platforms by using the appropriate message queuing software products. What is Message driven process? Ans . When messages arrive on a queue, they can automatically start an application using triggering. If necessary, the applications can be stopped when the message (or messages) have been processed. What are advantages of the MQ? Ans. 1. Integration. 2. Asynchrony 3. Assured Delivery 4. Scalability. How does it support the Integration? Ans. Because the MQ is independent of the Operating System you use i.e. it may be Windows, Solaris,AIX.It is independent of the protocol (i.e. TCP/IP, LU6.2, SNA, NetBIOS, UDP).It is not required that both the sender and receiver should be running on the same platform What is Asynchrony? Ans. With messag

XML Binding with JAXB 2.0 - Tutorial

Java Architecture for XML Binding (JAXB) is an API/framework that binds XML schema to Java representations. Java objects may then subsequently be used to marshal or unmarshal XML documents. Marshalling an XML document means creating an XML document from Java objects. Unmarshalling means creating creating a Java representation of an XML document (or, in effect, the reverse of marshaling). You retrieve the element and attribute values of the XML document from the Java representation. The JAXB 2.0 specification is implemented in JWSDP 2.0. JAXB 2.0 has some new features, which facilitate the marshalling and unmarshalling of an XML document. JAXB 2.0 also allows you to map a Java object to an XML document or an XML Schema. Some of the new features in JAXB 2.0 include: Smaller runtime libraries are required for JAXB 2.0, which require lesser runtime memory. Significantly, fewer Java classes are generated from a schema, compared to JAXB 1.0. For each top-level complexType, 2.0 generates a v