Thomas (boggyb) wrote,

  • Mood:
  • Music:

Java puzzle

Something a colleague came up with at work the other day...

Consider the following Java classes:

public class FooBase {};

public class Foo extends FooBase {};

public class Bar {
  public Bar(FooBase) {
    System.out.println("Constructor Bar(FooBase) called");

  public Bar(Foo f) {
    System.out.println("Constructor Bar(Foo) called");

public class Test {
  public static void testSomething() {
    java.util.ArrayList<FooBase> list = new ArrayList<FooBase>();
    list.add(new Foo());
    FooBase item = list.get(0);
    Bar b = new Bar(item);

Without compiling and running the program (because that would be too easy a way to solve this), what do you think will happen when you call Test.testSomething()?

My guess is that it will print "Constructor Bar(Foo) called", because while item is a reference of type FooBase the object being pointed to by item is actually of type Foo. But then the guy who came up with this pointed out that the output "Constructor Bar(FooBase) called" would also make sense, and if this were C++ that would be the expected output. The difference is all C++ knows is that it has a pointer to something that must be a FooBase, while Java knows that it has a pointer to something that is actually a Foo.

Tags: java, programming, puzzle

  • New shiny toy!

    The Nyx replacement build has been in the planning for a long time. It was originally pencilled in for late 2019, and looking at my notes would have…

  • Achievement unlocked: jump-starting my car!

    Headed out to sainsbury's just now - or tried to, only to discover that my car's battery had run down over the past week and just did not want to…

  • Pancakes!

    Since people have been prodding me for an update, here's a pancake-themed one (as everyone's blogging about pancakes today!). Unlike in the linked…

  • Post a new comment


    default userpic
    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.