getClass():
the getClass() method is used to get the runtime class (i.e., the actual class object) of
an object.
It returns an object of the Class type — from the [Link] package.
Observation:
1. You run the compiler
javac Test_43_nov08.java
javac reads the source file Test_43_nov08.java .
2. .class files are produced
The compiler generates bytecode files:
Test_43_nov08.class
A_nov08.class
3. Then we run java Test_43_nov08.java
4. JVM checks if Test_43_nov08.class is present in the memory, if not The JVM's class
loader loads java_nov08.Test_43_nov08
5. Execution starts from main method
6. when A_nov08 a = new A_nov08(); this is what's happening internally:
ClassLoader loads A_nov08.class
and creates a Class object in the JVM (an instance of [Link] , yes there is
a class name Class ) that represents the metadata(contains information like class
name java_nov08.A_nov08 , method info, constructor info etc.) of A_nov08 .
7. then at Class c = [Link]();
getClass() returns runtime class of a ( Class object for A_nov08 , which got
created earlier)
since it returns that same Class object, we store it inside c which is from Class
type.
8. Finally [Link]() returns the fully qualified class name
( getName() belongs to the [Link] class.)
toString():
toString() in Java returns a unique string representation of an object. It’s defined in Object
class.
Observation:
When you print an object ( using [Link](c) ),
the toString() method is automatically called behind the scenes.
As you can see in the program above they both have the same value.
The output is java_nov08.C_nov08@4dd8dc3
and this is how it gets generated:
we already getClass() and getName( ) methods
as for [Link](hashCode()) it converts the object’s hash code (an int) into
a hexadecimal string ( hashCode() method studied in Java_05_11_25).
for the next example we override toString() in B_nov08 which indirectly extends to Object
class( like any other class):
Obviously the child class B_nov08 prioritizes its own method (overridden toString() ) and
hence the output.
when a program run this is what happens :
Step Class Loaded When Why
1 [Link] , System , Class , etc. Automatically Core runtime classes
2 java_nov08.Test_44_nov08 At program start Entry point ( main )