Re: Static methods overridden !!



On Mar 25, 9:55 am, "Ravi" <v.r.san...@xxxxxxxxx> wrote:
Hi,

Consider the following piece of code

class AnimalTest {
public static void saySomething() {
System.out.println(" AnimalTest!");
}

}

class CowTest extends AnimalTest {
public static void saySomething1() {
System.out.println(" CowTest!");
}

public static void main(String[] args) {
AnimalTest[] animals = { new AnimalTest(), new CowTest() };
for (AnimalTest a : animals) {
a.saySomething();
}
new CowTest().saySomething();
}

}

Interestingly it prints out AnimalTest! thrice. I am wondering how did
it compile as CowTest doesn't have the method saySomething. Does the
static method got carried over to the subclass??

Regards,
Ravi

Static methods are Class level, so it doesn't matter WHAT object type
you have.

As a matter of fact, the following WILL work.

CowTest ct = null;
ct.saySomething();

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

Hope this helps,
Daniel.

.



Relevant Pages

  • Static methods overridden !!
    ... public static void saySomething() { ... class CowTest extends AnimalTest { ... public static void saySomething1() { ...
    (comp.lang.java.programmer)
  • Re: Static methods overridden !!
    ... compile-time type to look for the first matching method at runtime. ... Since CowTest "is-an" AnimalTest, the invocation from CowTest can find the method in AnimalTest. ... However, if CowTest did have a matching static method, it wouldn't override the superclass static method, it would hide the superclass static method. ...
    (comp.lang.java.programmer)
  • Re: Static methods overridden !!
    ... Since CowTest "is-an" AnimalTest, the invocation from CowTest can find the method in AnimalTest. ... However, if CowTest did have a matching static method, it wouldn't override the superclass static method, it would hide the superclass static method. ...
    (comp.lang.java.programmer)