Overloading Overriding
Table of Contents

Overloading

Overriding

Overriding is generally applicable to instance methods and NOT for any instance variables, static methods, static variables. For all the rest, they happen to be called as hiding.

class A{
   int t=10;
}
class B extends A{
   int t=20;
}
public class TestSuper{
   public static void main(String arg[]){
      A a=new B();
      System.out.println(a.t);
  }
}

The output when you run, it should be "20" as expected. But the output what we get is "10" instead of "20".

Reason [by Srinivasan M]:
Please note that overriding is applicable only for instance methods. In case of variables, overriding is not applicable and field hiding is only applicable. A subclass can only hide the fields of a superclass and it cannot override them. Also note, when you access the field of an object, the type of the reference (here it is object A) will be accessed and not the class of the object which is denoted by the reference (here it is object B). Hence, 10 is outputted.

Generally, note that overriding is applicable only for instance methods. Only in that case, you need to see which object is actually being referred in runtime.

In all other cases (instance variables, static variables and static methods), overriding is not applicable and only hiding happens. In this case, the type of the reference will be accessed and it will be resolved during compile time itself.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.