Reputation: 248
I am a new learner of JAVA Language. In JAVA the Object class is the root class (or) top most Super class in the class hierarchy (every class is a subclass of Object). So every class we create have the 11 methods (as mentioned in JAVA API) of the Object class and we can use them, like the toString()
method.
But the definition of the toString()
method uses a method getName()
which is not defined in Object class. (I know that the toString()
method uses the getName()
method because I have used jd-gui to view the source code of the Object.class file installed in my pc.)
If we create a java file
class test {
public static void main(String args[]) {
test t = new test();
System.out.println(t.getClass().getName());
/* Don't understand how I am able to use getName() method without extending any other
*class containing *getName() method.*/
}
}
The above gives "test" as the output without error.
Coming to Object class it is the root class so it is not extending any other classes and to do any work it should define its own methods.
My Question is,
How are the Object class and classes we define able to use this method without defining the getName()
method in their class?
Are any other classes are extended by besides the Object class?
Upvotes: 1
Views: 7409
Reputation: 393851
getName()
is a method of the Class
class, not the Object
class. Object
has a getClass() method that returns a Class
instance.
t.getClass()
returns an instance of Class<test>
, which has the method getName().
This allows you to call t.getClass().getName()
.
Upvotes: 7