Clarification about Overriding methods
When i invoke a overridden method from within the base class, it always calls the method present in the derived class.
Further I'm presenting you a sample code to describe the same.
Confuse.java
class Base {
int i;
Base() {
add(1);
}
void add(int v) {
System.out.println("\nBASE() = "+v);
}
}
class Extension extends Base {
Extension() {
add(2);
}
void add(int v) {
System.out.println("\nEXTENSION() = "+v);
}
}
public class Confuse {
public static void main(String[] args) {
bogo(new Extension());
}
static void bogo(Base b) {
b.add(8);
}
}
OUTPUT :
EXTENSION() = 1
EXTENSION() = 2
EXTENSION() = 8
Could you please clarify me on the same ?
Thanks
# 1
Hi Vikas,
First, note that this forum is devoted to Sun Java Studio Creator IDE. General Java questions can be asked on forums here: http://forum.java.sun.com/
Second, your code works as designed. Let's see what happens when you call
new Extension();
1) constructor method Extension() called
2) constructor of parent method Base() called
3) constructor of parent method java.lang.Object() called
4) virtual methods table is created for newly created object of Extension class
5) return to Base() method
6) add(1) is called via virtual methods table; it's Extension.add(1)
7) return to Extension() method
8) add(2) is called via virtual methods table; it's Extension.add(2)
So all is OK. If you call bogo(new Base()), you'll get output BASE()=...
Thanks, Misha
(Creator team)