• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to read this program?

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ran into a program that appears to difficult to dicipher. Help. The result 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();
}
}
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First you have to see that the actual object being created is an instance of class Extension. Thus, all invocations of the add() method will be resolved to the one in class Extension. When the object is constructed, add is invoked with argument 1 (i is now 2) first and then 2 (i is now 6). Then, add(8) is invoked, which changes i's value to 6+(2*8) = 22.
A little piece of friendly advice: If you found this code difficult to read, you might want to spend some time in the beginner forum since you may not have grasped the fundamentals of polymorphism. That's just an advice, though
You might find the following story about polymorphism interesting: How my Dog learned Polymorphism
[ April 03, 2002: Message edited by: Valentin Crettaz ]
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic