Tuesday, 14 April 2009

Hiding Vs Overriding! Interesting!!

package test;

class FieldHiding { 

public String InstanceField = "Instance Field in SuperClass"; 

public static String StaticField = "Static Field in SuperClass"; 

public static int StaticIntField = 1; 


public class FieldHidingDemo extends FieldHiding { 

public String InstanceField = "Instance Field in SubClass"; 

public String StaticField = "Static Field changed to Instance Field in SubClass"; 

protected String StaticIntField = "public static int in super class -> protected String in subclass";

public static void main(String[] args) { 

FieldHiding fieldHiding1 = new FieldHiding(); 

FieldHiding fieldHiding2 = new FieldHidingDemo(); 

FieldHidingDemo fhd = new FieldHidingDemo();













This example is from geekexplains.blogspot.com


Fields and static methods cannot be overridden. They are just hidden.


What is overriding?

Binding is done depending upon the type of calling object, not on the type of reference used.


And what is hiding?

Binding is done depending upon the type of reference used, not on the type of calling object.


Field Hiding:

We can narrow or widen the visibility of variables. i.e. a public variable in superclass can be made private in subclass and vice-versa.


Static Method Hiding:

We cannot narrow the visibility of functions. But we can widen.


Good link for this. Specially the last question. ;)


In java, non-static methods are always overridden and static methods are always hidden when they are redefined in subclass. 

But in C#, there are options to either hide or override the method. It is possible with some combinations of keywords new, virtual and override.

No comments: