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

Help with this one from Markus Green's mock exam

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What will happen when you attempt to compile and run the following code?
class Base {
int i=99;
public void amethod(){
System.out.println("Base.amethod()");
}
Base(){
amethod();
}
}
public class RType extends Base{
int i=-1;
public static void main(String argv[]){
Base b = new RType();
System.out.println(b.i);
b.amethod();
}
public void amethod(){
System.out.println("RType.amethod()");
}
}
The answer is:
RType.amethod
99
RType.amethod
Why is not:
Base.amethod
99
RType.amethod
 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
that is becuase the method amethod() in class Base, has been overriden by the method amethod() in class RType.
so when we reach the line
Base b = new RType();
the constructor of the super class Base is called first,inside it, a call to the method amethod() is made, remember that this method has been overriden by the subclass, so it will call the overriden version of it, which will be inside the class RType.
so we get "RType.amethod" written to the output.
instead of the "Base.amethod()".
hope this helps
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Esenih,
I had a similar question not long ago. As I understand this, variable references are determined at compile time by reference type and method references are determined at runtime by object type. In this case, when the base classes' constructor is called, the reference to amethod is determined to be RType because that is what type the object is.
 
If you have a bad day in October, have a slice of banana cream pie. And this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic