There are some issues here:
- as other has already said -
hashCode() returns an integer, and you might be confusing with toString()
- Which is more important IMO:
Object has both hashCode() and toString() methods. However, any subclass of Object can override this method. When the method will be called - the dynamic type's method will be invoked, so for String, String.hashCode() will be invoked and not Object.hashCode() [same idea for toString()]. This is called dynamic dispatch.
for example:
public static class A {
public void foo() {
System.out.println("A");
}
}
public static class B extends A{
@Override
public void foo() {
System.out.println("B");
}
}
public static void main(String[] args) throws Exception {
A a = new B();
a.foo();
}
In the above code snap, B.foo() will be invoked, and B will be printed, since B overrides foo(), and the dynamic type of a is B, so B.foo() is invoked.
In your case: Since String overrides hashCode(), then String.hashCode() is invoked, while for testClass - it doesn't override hashCode(), so the original Object.hashCode() is invoked.
hashCode() is from Object class which is the mother of all class.String s = "hello";