Suggested Pages

Saturday, May 19, 2012

Overriding and Shadowing

Overriding


In Java, overriding applies to instance methods. The mechanism of method overriding is to run the method of the dynamic type at runtime.
Suppose you have the following classes:
A.java
public class A {
  public void doThis(){
      System.out.println("A");
  }
}
class B extends A{
  public void doThis(){
      System.out.println("B");
  }
}

class C extends B{
  public void doThis(){
      System.out.println("C");
  }
}

Main.java
public class Main {
  public static void main(String[]args){
          A a =new C();
          a.doThis();
  }
}
If we launch the above Main class we have the following output:
Console
  C
As you can see, the method of dynamic object type has been chosen.

Variable Shadowing


With regard to the instance variables the mechanism is called shadowing. Shadowing for instance variables depends on the static type and not dynamic type.
Suppose you have the following classes:
A.java

 package a;
 
 public class A {
   int variable=1;
 }

 class B extends A {
   int variable=2;
 }

 class C extends B {
   int variable=3;
 }

Main.java
 public class Main {

  public static void main (String [] args){
     A a =new C();
     System.out.println(a.variable);     
     B b=new C();
     System.out.println(b.variable);  
 
  }

 }

If we launch the above Main class we have the following output:
Console
     1  
     2
As you can see the static type has been chosen. The instance variable printed on the console depends only on the static type.

Method shadowing


We cannot say that overriding applies to static method. If you create a static method in the subclass with the same signature, at runtime you will not see overriding for that method.
A.java
 package a;
public class A {
     public static void doThis() {
           System.out.println(“A”);
     }
 }

class B extends A {
     public static void doThis() {
         System.out.println(“B”);
     }
}

Main.java
 public class Main {

  public static void main (String [] args){
    A.doThis();     
    B.doThis();  
 
  }

 }
If we launch the above Main class we have the following output:
Console
    A
    B
As you can see the static type has been chosen. The static method chosen only depend on the static type.

No comments :

Post a Comment

Suggested Pages