Re: Static methods overridden !!



Ravi wrote:
Well, the class doesn't have the method at all ! Please refer the
original code again. CowTest class doesn't have saySomething method at
all . It has saySomething1 (1 (one) extra in the end, may be I should
have made this more clearly differentiating). I am not referring the
objects here and I am clear on the fact that objects have nothing to
do with invocation of static methods.

you can replace new CowTest().saySomething(); with
CowTest.saySomething(); if it makes things simpler.
Yes.

Clearly saySomething comes from super class. This is confusing for
me.

Regards,
Ravi



What is going in is that the compiler is determining /at compile time/ what the method to be called is, based on the declaration of the variable. For example, this will not compile:

Object foo = new AnimalTest();
foo.saySomething();

because method Object does not have a method 'saySomething'. The compiler is using the declaration of the variable (Object in my example, AnimalTest in yours) to determine what static method to call. At no point does the actual type come into play. For example, this:

((AnimalTest)new Object()).saySomething();

will compile and is equivalent to this:

AnimalTest.saySomething();

even though it would throw a ClassCastException if it were an instance method, like so:

class Foo {
public void bar() {}
public static void main(String[] args) {
((Foo)new Object()).bar();
}
}

Hope this helps.
.