0

By runnung the following code I got the result:

method from class A
method from class B.

public class Test {

    static class A {

        public A() {
            someMethod();
        }

        public void someMethod() {
            System.out.println("method from class A");
        }
    }

    static class B extends A {
        public void someMethod() {
            System.out.println("method from class B");
        }
    }

    public static void main(String... args) {
        new A();
        new B();
    }
}

The first line of the result is clear but the second one isn't. Why didn't the constructor of the class A call the method defined in class A instead the overriden method of class B? Can it be that after compilation the code from constructor A is somehow copied to class B so that we actually call our method from class B?

Adnan Alicic
  • 29
  • 1
  • 4
  • This is a significant difference between Java and C++. C++ behaves as you are expecting here. Java doesn't. You would have to ask James Gosling the reason why. – user207421 May 13 '12 at 01:44
  • Im not that familiar with C++ anymore. Do C++ constructors call their parent constructors without explicitly being written to do so? Is that what the o.p. is expecting? – Mark Sholund May 13 '12 at 11:48

1 Answers1

3

The second object is of type B, so when the method someMethod is invoked in the constructor, it takes the last method declaration of this method for type B.

MByD
  • 135,866
  • 28
  • 264
  • 277