views:

107

answers:

2

Hello, recently I went through the inheritance concept.

As we all know, in inheritance, superclass objects are created/initialized prior to subclass objects. So if we create an object of subclass, it will contain all the superclass information.

But I got stuck at one point.

Do the superclass and the subclass methods are present on separate call-stack? If it is so, is there any specific reason for same? If it is not so, why they don't appear on same call-stack?

E.g.

// Superclass
class A {
    void play1( ) {
        // ....
    }
}

// Subclass
class B extends A {  
    void play2( ) {  
        //.....   
    }
}

Then does the above 2 methods i.e play1( ) and play2( ) appear on separate call stack?

Thanks.

+2  A: 

There is only one call stack per thread - so no, both playX calls happen on the same stack.

I'm not sure why you think they wouldn't, or what this has to do with inheritance. Perhaps if you gave a specific example of why you think this is important (i.e. a case where the behaviour would be notably different) it would help to address what is presumably a deeper issue.

Andrzej Doyle
+3  A: 

There is not necessarily any relation between a call stack and inheritance. In fact frequently there isn't. If a superclass method is overridden in a child then it is the child's method that is called - the superclass method is not executed at all, unless there is code to explicitly do that in the child method. The superclass method will not appear at all in the call stack - unless it is called explicitly by the child method.

class A {
  void play1() {
    //...
  }
  void play2() {
    //....
  }
}
class B extends A {
  void play1() {
    //...
  }
}
B b = new B();
b.play1(); // 'first' call
b.play2(); // 'second' call

A.play2() appears on the call stack only during "second call". B.play1() appears on call stack only during "first call". A.play1() never appears on the call stack and is never executed.

DJClayworth
Ok ! you mean to say that superclass method appears only when it is called by subclass object explicitly.
Mandar