Win a copy of TDD for a Shopping Website LiveProject this week in the Testing forum!
  • 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

From the office.

 
Greenhorn
Posts: 5
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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!!

 
Ranch Hand
Posts: 451
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


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
Posts: 5
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That's correct.
Naturally I would have assume that at runtime the JMV would sort it out and use MySubObj.
 
We can fix it! We just need some baling wire, some WD-40, a bit of duct tape and this tiny ad:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic