Re: Static methods overridden !!



Ravi wrote:
Static calls are really replaced by CowTest.saySomething() (which it
inherits from AnimalTest)

Yep, I understand that Static method calls are at class level than at
object level. But, are you trying to say that static methods will be
inherited but not overridden? This is strange and confusing. Can you
please try n explain from JVM point of view? Thanks.

Will you accept an explanation that's not from the JVM
point of view, but from the Java language point of view?

Static methods can't be overridden, because there's no
polymorphism involved. For instance methods, the choice of
which method is called depends on the actual class of the
object that is referenced -- on the `this', if you like:

Object thing = "Hello, world!";
System.out.println(thing.toString()); // String's method
thing = new File("forty.two");
System.out.println(thing.toString()); // File's method

But with static methods there is no `this' to determine
which method to call. You write Classname.doit(42), and
as expected you call the static doit() method of the class
Classname. Observe that in this form there is *no* object
instance to govern the selection of different doit() methods;
you will always and only get the doit() of Classname, and not
some other class' doit().

The confusion arises when you don't write the class name,
but instead use a reference variable: thing.doit(42). Many
people find it odd that Java even permits this form, and some
go so far as to call it a flaw in the language (I'm not enough
of a connoisseur to have an opinion), but for reasons good or
bad the form is legal. But it still doesn't mean that Java
checks the class of the object `thing' refers to to decide
which doit() to call; Java calls the doit() method of the class
that matches the declared type of the `thing' reference. Indeed,
as Daniel Pitts pointed out, `thing' need not even be a valid
object reference at all:

Classname thing = null;
thing.doit(42); // Classname's method

You can explore this a little more by making a few simple
alterations to your original code sample, coming up with
something like

class Animal {

public static void main(String[] unused) {
Animal[] zoo = {
new Animal(), new Dog(), new Beagle(), null };
for (Animal a : zoo) {
System.out.println(a.getName());
}
}

static String getName() { return "Animal"; }
}
class Dog extends Animal {
static String getName() { return "Dog"; }
}
class Beagle extends Dog {
static String getName() { return "Beagle"; }
}

What output do you expect? What would you expect if the
final three `static' keywords were removed? Make your
predictions, then try it both ways and see.

--
Eric Sosman
esosman@xxxxxxxxxxxxxxxxxxx



.