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");
    }
}

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

Why do we get instanceMethod from Bar, but classMethod() from Foo? Aren't we using the same instance f to access both of these?

Edited 3 Years Ago by Dani: Formatting fixed

Class methods cannot be overridden in Java. Calls to class methods are resolved using the declared type of the variable (not the actual type of the Object it refers to) - Foo in this case. Instance methods are overridable and are resolved using the actual Object.

http://stackoverflow.com/questions/5059051/java-calling-a-super-method-from-a-static-method

PS - if you have the full compiler diagnostics running you will get warning "static method ... should be accessed in a static way". ie although f.classMethod(); is valid Java, you are advised to code it as Foo.classMethod(); to avoid any confusion.

Edited 5 Years Ago by JamesCherrill: Added link, ps

This article has been dead for over six months. Start a new discussion instead.