This week's book giveaway is in the Programmer Certification forum.
We're giving away four copies of OCP Oracle Certified Professional Java SE 21 Developer (Exam 1Z0-830) Java SE 17 Developer (Exam 1Z0-829) Programmer’s Guide and have Khalid Mughal and Vasily Strelnikov on-line!
See this thread for details.
  • 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:

polymorphy again

 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
dear people, the link works http://members.spree.com/education/javachina/Cert/Polymorphism.html
please explain me the following in some more steps.

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;
}
}
//Display 23, think why?

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The code u have written is quite complicated.Here is the explanation (i think)
1)when u pass the subclass object new Sub1() to m() the constructor for Sub1() will run.In it there is no explicit call to super so compiler inserts it's own call and so Base1() cons. will get called
2)Inside Base1() cons. there is a call to the add() method with param 1.Now here is the trick.The add() method in the SUBCLASS will be called because u have overridden the method.Hence i will get the value
1+(1*2)ie i=3
3)When control comes back to Sub1() cons add() is called with param 2.Hence i now gets the value 3+(2*4)ie i=7
4)Control now passes back to main and add is called with param 8.Hence i now gets the value 7+(2*8)ie i=23
This is an example of rumtime poly.The object makes it's own interpreation of the request u send it.In this case method in SUBCLASS will get called.Don't override and observe result
I hope i have answered correctly.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry .Step 3) should be
i=3+(2*2)ie i=7
 
reply
    Bookmark Topic Watch Topic
  • New Topic