1

I'm trying to find the hierarchy of the Object - "String" using the below method.

public class test{

    public static void main(String[] args){
        String x = "Test";
        System.out.println(x.getClass().getClass());
    }
}       

The first x.getclass() return

Output:

    class java.lang.String

then -System.out.println(x.getClass().getClass());

Output:
       class java.lang.Class

and anything after that yields the same result

System.out.println(x.getClass().getClass().getClass().getClass());

Shouldn't it at some point lead to - java.lang.Object??

2 Answers 2

4

Result is correct since you are calling getClass() on Class instance. To get parent class you should call getSuperclass() from Class instance that represents subclass type.

String x = "Test";
System.out.println(x.getClass().getSuperclass());

Output

class java.lang.Object
Sign up to request clarification or add additional context in comments.

Comments

1

x.getClass().getClass() will always return the class object representing java.lang.Class for any non-null value x.

That's because x.getClass() can only return a Class object and you're asking that class object what type it is (obviously: Class).

What you seem to want to try is not x.getClass().getClass() but x.getClass().getSuperClass(). Repeating that last part will eventually lead to java.lang.Object, as you expected (and, if repeated one more time, to null).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.