This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Overriding or Overloading problem" Watch "Overriding or Overloading problem" New topic

Overriding or Overloading problem

Saurabh Gupta

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(; //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

Joined: Jul 08, 2003
Posts: 24199

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]
I agree. Here's the link:
subject: Overriding or Overloading problem
It's not a secret anymore!