• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Polymorphism

 
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
can somebody please explain me how this program works:
import java.io.*;
public class Polymorphism {
static void m(Base1 b){
b.add(8);
b.print();
}
public static void main(String[] args) throws IOException {
m(new Sub1());
System.in.read();
}
}
class Base1 {
int i = 1;
Base1(){
add(1);
}
void add(int n){
i+=n;
}
void print() {
System.out.println(i);
}
}
class Sub1 extends Base1{
Sub1(){
add(2);
}
void add(int n){
i+=n*2;
}
}
the output is 23.
 
mister krabs
Posts: 13974
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Couldn't pick a simpler one, huh?
OK, here goes.
1) we are creating a new Sub object so run the constructor of Sub.
2) Before running Sub's constructor since Sub's constructor doesn't run any parent constructor run the empty constructor of Base1.
3) Base1 runs add() but add has been overridden by Sub so run the add() method of Sub. (i = 3)
4) Now run Sub's constructor which runs the add() method of Sub (i = 7)
5) Run m() which runs the add() method which has been overridden by Sub (i=23)
6) Print the result.
 
reply
    Bookmark Topic Watch Topic
  • New Topic