?

Log in

No account? Create an account
Java puzzle - 'Twas brillig, and the slithy toves did gyre and gimble in the wabe [entries|archive|friends|userinfo]
Thomas

[ website | Beware the Jabberwock... ]
[ deviantArt | the-boggyb ]
[ FanFiction | Torkell ]
[ Tumblr | torkellr ]

Links
[Random links| BBC news | Vulture Central | Slashdot | Dangerous Prototypes | LWN | Raspberry Pi]
[Fellow blogs| a Half Empty Glass | the Broken Cube | The Music Jungle | Please remove your feet | A letter from home]
[Other haunts| Un4seen Developments | Jazz 2 Online | EmuTalk.net | Feng's shui]

Java puzzle [Thursday 27th January 2011 at 11:23 pm]
Thomas

boggyb
[Tags|, , ]
[Feeling |curiouscurious]
[Playing |Go the Distance (I'll Go) ~ Sixto Sounds/RTIST OverClocked ReMix]

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.

Link | Previous Entry | Share | Next Entry[ 2 pennies | Penny for your thoughts? ]

Comments:
[User Picture]From: 13th_einherjar
Friday 28th January 2011 at 1:16 am (UTC)
I think the code will fail to compile. The ArrayList is not genericized - it holds references to Objects, so "Foobase item = list.get(0);" will require a cast. It will then call the FooBase constructor, because if Java were to determine that it was actually a Foo, it would be a dynamically typed language and would not need things like generics.
(Reply) (Thread)
[User Picture]From: boggyb
Friday 28th January 2011 at 5:47 pm (UTC)
Whoops, forgot to escape the angle brackets. Post updated.

You are correct that without the <FooBase>, the code will fail to compile.
(Reply) (Parent) (Thread)