3

In Java, "this" refers to the current object. I assumed that "this" is the same type as the current object, but consider this example:

class A {
    static void f() {
        System.out.println("A.f");
    }
    void g() {
        this.f();
    }
}
class B extends A {
    static void f() {
        System.out.println("B.f");
    }
}
public class C {
    public static void main(String[] args) {
        B test = new B();
        h(test);
    }
    static void h(B x) {
        x.g();
    }
}

The result is:

A.f.

Which I don't understand, because when x.g() is called, x is of type B. In the x.g() call, g is looked up in B, then in A (because B subclasses A). g then calls f, an instance method of both A and B, meaning that the version of f called depends on the type of the implicit THIS parameter. I would assume that B.f() would be called since X is of type B, but this is not so.

What type does THIS take on, exactly?

Leon Helmsley
  • 575
  • 2
  • 6
  • 17

1 Answers1

3

static methods are not inherited. When you call

static void h(B x) {
    x.g();
}

You are calling g() declared in class A which calls

static void f() {
    System.out.println("A.f");
}

Methods are resolved on the static type of the reference they are called on. For instance methods, polymorphism and late-binding do their trick to execute the actual method. However, since late binding doesn't apply to static methods, you are calling A.f().

You can call static methods on instance references and they are resolved on their declared type. This is not recommended.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 1
    And that's why you get a compiler warning here. – Thilo Oct 08 '13 at 02:20
  • I'm confused. This link http://stackoverflow.com/a/10292034/2288418 says all accessible methods are inherited. Besides, if it wasn't inherited, would that result in a compile time error (trying to lookup g in B when x.g()? – Leon Helmsley Oct 08 '13 at 02:25
  • 1
    As that answer states, say your child class doesn't declare a `static` method with the same name as a `static` method in the parent class. In this case, because your child class is still the same type as its parent, you can still access the `static` method through a reference or through the class identifier directly. – Sotirios Delimanolis Oct 08 '13 at 02:27