0
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 by Dani: Formatting fixed

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by JamesCherrill
0

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 by JamesCherrill: Added link, ps

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.