aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Help with this one from Markus Green's mock exam Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Help with this one from Markus Green Watch "Help with this one from Markus Green New topic
Author

Help with this one from Markus Green's mock exam

Esenih Camai
Greenhorn

Joined: Jan 07, 2001
Posts: 8
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
Maitham H
Greenhorn

Joined: Jan 07, 2001
Posts: 29
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


A Software life cycle can be greater than its Developer's
Scott Kiel
Greenhorn

Joined: Jan 05, 2001
Posts: 15
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.
 
 
subject: Help with this one from Markus Green's mock exam