aspose file tools*
The moose likes Java in General and the fly likes Overriding or Overloading problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Overriding or Overloading problem" Watch "Overriding or Overloading problem" New topic
Author

Overriding or Overloading problem

Saurabh Gupta
Greenhorn

Joined: Oct 06, 2007
Posts: 18
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

Joined: Sep 04, 2007
Posts: 71
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.


SCJP 1.5
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.


[Jess in Action][AskingGoodQuestions]
 
Consider Paul's rocket mass heater.
 
subject: Overriding or Overloading problem