001package beginner;
002
003import com.sandwich.koan.Koan;
004
005import java.text.MessageFormat;
006import java.util.ArrayList;
007import java.util.List;
008
009import static com.sandwich.koan.constant.KoanConstants.__;
010import static com.sandwich.util.Assert.assertEquals;
011
012public class AboutObjects {
013
014    @Koan
015    public void newObjectInstancesCanBeCreatedDirectly() {
016        assertEquals(new Object() instanceof Object, __);
017    }
018
019    @Koan
020    public void allClassesInheritFromObject() {
021        class Foo {
022        }
023
024        Class<?>[] ancestors = getAncestors(new Foo());
025        assertEquals(ancestors[0], __);
026        assertEquals(ancestors[1], __);
027    }
028
029    @Koan
030    public void objectToString() {
031        Object object = new Object();
032        String expectedToString = MessageFormat.format("{0}@{1}", Object.class.getName(), Integer.toHexString(object.hashCode()));
033        assertEquals(expectedToString, __); // hint: object.toString()
034    }
035
036    @Koan
037    public void toStringConcatenates() {
038        final String string = "ha";
039        Object object = new Object() {
040            @Override
041            public String toString() {
042                return string;
043            }
044        };
045        assertEquals(string + object, __);
046    }
047
048    @Koan
049    public void toStringIsTestedForNullWhenInvokedImplicitly() {
050        String string = "string";
051        Integer i = new Integer(128);
052        Short s = new Short((short) 15);
053        assertEquals(string + " " + i + " " + s, __);
054    }
055
056    private Class<?>[] getAncestors(Object object) {
057        List<Class<?>> ancestors = new ArrayList<Class<?>>();
058        Class<?> clazz = object.getClass();
059        while (clazz != null) {
060            ancestors.add(clazz);
061            clazz = clazz.getSuperclass();
062        }
063        return ancestors.toArray(new Class[]{});
064    }
065
066}