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

Overriding or Overloading problem

 
Saurabh Gupta
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please explain the output of this program.
This program is giving output as "TRUE".

===============================================
class Base {
public boolean foo(Base b) {
return true;
}
}
class Sub extends Base{

public boolean foo(Sub s) {
return false;
}

}


public class TestClass {
public static void main(String argv[]) {
Base bb = new Base();
Base bs = new Sub();
Sub ss = new Sub();


System.out.println(bs.foo(ss)); //true ???

}
}
==============================================================
 
greg buela
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
bs is a Base reference, so, even if it references a Sub instance, you can only call methods defined (or declared) in Base through a Base reference. Method foo() in Sub is not overriding foo() in Base. If it had the same signature, it would work polymorphically, but here the signature is different. So, in Sub you have foo() as defined in Sub and the other one inherited from Base---both are available. But from a Base reference only the superclass version is available.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Everything Greg says is correct. I just wanted to add a reminder that it's up to the compiler to choose between overloaded methods, and that choice can only consider the declared type of the reference variable you're calling the method on -- i.e., the actual class of the object is not considered.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic