This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can Any Explain This Code...

 
Thangaraj Selvamani
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class SuperCafe4Java {
public Object get (Object o) {
return ("SuperCafe4Java");
}
}

class SubCafe4Java extends SuperCafe4Java {
public Object get (String o) {
return ("SubCafe4Java");
}
}

class TestCafe4Java {
public static void main (String[] arguments) {
SuperCafe4Java superFoo;
SubCafe4Java subFoo;

superFoo = new SubCafe4Java();
System.out.println (superFoo.get("super"));

subFoo = new SubCafe4Java();
superFoo = subFoo;
System.out.println (superFoo.get("super"));
}
}

OutPut:SuperCafe4Java
SuperCafe4Java
 
Ankit Garg
Sheriff
Posts: 9509
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well the output is

SuperCafe4Java
SuperCafe4Java

because get(Object o) is not overridden by get(String o). Instead the two methods are overloaded. So when you call get("super") with a SuperCafe4Java class reference, the compiler looks for a method matching get("super") in the SuperCafe4Java class. It finds the get(Object o) method matching this method (as get(String o) is not available in SuperCafe4Java). So that method is called.
 
M Srilatha
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here get() method of SuperCafe4Java is overloaded in the sub class SubCafe4Java.
Its not overridden.(Overridden method calls will be determined at run time)
And the calls to the overloaded methods will be determined at compile time.

So the get method in SuperCafe4Java will be executed not the one in SubCafe4Java.

See page 109 of K&B 5.0 for more info!

Hope this is clear!
 
Thangaraj Selvamani
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But When Im Running This Two Code...Getting Different OutPut




 
M Srilatha
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Thangaraj Selvamani
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you...My Doubt Has got cleared...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic