• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

super class

 
Arivu Selvi
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anybody explain how the output here is 22?

class Base {
int i;
Base() { add(1); }
void add(int v) { i += v; }
void print() { System.out.println(i); }
}

class Extension extends Base {
Extension() { add(2); }
void add(int v) { i += v*2; }
}

public class Qd073 {
public static void main(String[] args) {
bogo(new Extension());
}
static void bogo(Base b) {
b.add(8);
b.print();
}
}
 
Joe Harry
Ranch Hand
Posts: 10080
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question is explained in the Khalid Mughal's book itself.
 
Vishal K Patel
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here, when the is called, automatically super constructor will be called.

Form the super constructor, add method is called with argument 1. but the method from child class will be executed at run time as the original object is from child class.

This is the good example of polymorphisms.

I think it's enough to get the reason.....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic