IntelliJ Java IDE
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes From the office. Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "From the office." Watch "From the office." New topic
Author

From the office.

Jean-Francois Alban
Greenhorn

Joined: Apr 13, 2011
Posts: 5
Hi guys

Here's a code we were playing with at the office.
What do you think is the expected outcome (no cheating don't run).
Also please provide a why to your answer. Thanks guys!!

Helen Ma
Ranch Hand

Joined: Nov 01, 2011
Posts: 319

public class Toto {

public static void main(String[] args) {
Toto toto = new Toto();
System.out.print(toto.toString(toto.getMyObj()));
}

MyObj getMyObj(){
return new MySubObj();
}

String toString(MyObj swap){
return "MyObj";
}

String toString(MySubObj swap){
return "MySubObj";
}
}

class MyObj{

}

class MySubObj extends MyObj{

}
public class Toto {

public static void main(String[] args) {
Toto toto = new Toto();
System.out.print(toto.toString(toto.getMyObj()));
}

MyObj getMyObj(){
return new MySubObj();
}

String toString(MyObj swap){
return "MyObj";
}

String toString(MySubObj swap){
return "MySubObj";
}
}

class MyObj{

}

class MySubObj extends MyObj{

}



I think the answer is MyObj.
From the code , the toString method seems overloaded correctly.
Step 1. toto.getMyObj() returns a MyObj object which is actually a MySubObj.
Step 2. What is passed in as the argument of toto.toString()? an object of MyObj type
Step 3. So, the toString(MyObj swap) is called instead of toString(MySubObj)
Step 4 Therefore, it prints MyObj.
Correct me if I am wrong.
Jean-Francois Alban
Greenhorn

Joined: Apr 13, 2011
Posts: 5
That's correct.
Naturally I would have assume that at runtime the JMV would sort it out and use MySubObj.
 
 
subject: From the office.
 
Threads others viewed
Strings....
From main method to contractor, it is possible?
Inner Class
Arrays comparsion: int[].equals() vs Arrays.equals()
Possible Memory Leak ?
WebSphere development made easy
without the weight of IBM tools
http://www.myeclipseide.com

cast iron skillet 49er

more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture