• 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
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Please Explain ME how it works

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi all java Ranchers please Explain me how the code works...
it gives answer 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 foo
{
public static void main(String args[])
{
logo(new Extension());
}
static void logo(Base b)
{
b.add(8);
b.print();
}
}
 
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Dheeraj,
Lets step through the program starting a foo.main:
1. Create new Extension for logo method parameter
2. Extension constructor: compiler automatically places call to
base constructor as first line.
3. Base constructor (i = 0) calls add method with param = 1
4. Extension add method: i += 2 --> i = 2
5. Extension constructor calls add method with param = 2
6. Extension add method: i += 4 --> i = 6
7. Logo method calls add method with param = 8
8. Extension add method: i += 16 --> i = 22
9. Logo method calls print method
10. Base print method: prints out "22".
Regards,
Manfred.
 
Dheeraj Mhetre
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi Manfred.....
thank you for quick reply... now i got the answer...
that means " add " method of Extension class is called
thrice....
ok thank you...
dheeraj
reply
    Bookmark Topic Watch Topic
  • New Topic