Total Pageviews

Sunday, January 23, 2011

Overriding v/s Hiding


Consider the code snippet::


class Foo {
public static void classMethod() {
System.out.println(“classMethod() in Foo”);
}

public void instanceMethod() {
System.out.println(“instanceMethod() in Foo”);
}
}

class Bar extends Foo {
public static void classMethod() {
System.out.println(“classMethod() in Bar”);
}

public void instanceMethod() {
System.out.println(“instanceMethod() in Bar”);
}
}


Let's Consider the following main method to test above code


class Test {
public static void main(String[] args) {
Foo f = new Bar();
f.instanceMethod();
f.classMethod();
}
}



If you run this, the output is

instanceMethod() in Bar
classMethod() in Foo


Although f was declared as a Foo, the actual instance we created was a new Bar(). So at runtime, the JVM finds that f is a Bar instance, and so it calls instanceMethod() in Bar rather than the one in Foo. That’s how Java normally works for instance methods.


It would be better coding style to write either:

Foo.classMethod();

or

Bar.classMethod();

That way, it is crystal clear which class method you would like to call.





No comments:

Post a Comment