0

I have a quite simple question regarding the following code snippet.

public class SuperClass {

    public SuperClass() {
        this.test();  //Always invokes the overridden method in the sub-class.
    }

    public void test() {
        System.out.println("test() in SuperClass.");
    }
}

public final class SubClass extends SuperClass {

    public SubClass() {
        super();        
    }

    @Override
    public void test() {        
        System.out.println("test() in SubClass.");
    }
}

public final class Test {

    public static void main(String... args) {
        SubClass subClass=new SubClass();
    }
}

In this example, the only line in the main() method indirectly passes a call to the super class constructor in which it attempts to invoke the test() method as this.test().

The method invoked by this.test() in the super class constructor is however, the overridden method in SubClass.

Why doesn't the method call this.test() in the super class constructor invoke its own method in the super class itself (though this refers to the current instance by which this method is to be invoked)?

Tiny
  • 27,221
  • 105
  • 339
  • 599

2 Answers2

5

though[t] this refers to the current instance by which this method is to be invoked

It does, and the runtime type of that instance is SubClass, so the SubClass's method gets invoked.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

In object oriented programming, one of the ideas is that the object itself is responsible for how it operates on its data. Because you invoke a SubClass object, when you call test() on that object, from anywhere, you call SubClass's test() method. The this keyword refers to the current instance, which will refer to whatever the object was invoked as.

Nathan
  • 2,093
  • 3
  • 20
  • 33
  • It's a logical argument, but may be a little too general. For example, in C++ the equivalent code would invoke the superclass's `test()` method. – NPE Feb 17 '14 at 19:51
  • That's interesting to know. When I learned C++ I was taught to mark any method intended to be overridden as virtual so that's a behavior I've never actually seen. – Nathan Feb 17 '14 at 19:58
  • Confusingly, in C++ what I described happens with `virtual` methods: http://stackoverflow.com/questions/496440/c-virtual-function-from-constructor – NPE Feb 17 '14 at 20:00