Declaration of Class
:
The declaration of Class is shown below.
public final class Class<T> extends Object implements Serializable, GenericDeclaration, Type, AnnotatedElement
Here,
T
represents the type of class modeled by the
Class
object. For example, the type of
String.class
is
Class<String>
. Use
Class<?>
if the class being modeled is unknown.
Class has no
public
constructor. Instead Objects of type
Class
are created automatically by the
Java Virtual Machine
, when classes are loaded. Gnerally, we obtain a
Class
object by calling the
getClass()
method defined by
Object
class.
Class methods:
class
class sample
{
public static void main(String arg[])
{
X x = new X();
Y y = new Y();
Class<?> clObj; // LINE A
clObj = x.getClass();
System.out.println("X is object of class : " + clObj.getClass()); // LINE B
/*if (clObj.equals(x))
{
System.out.println("clObj and x are the references of same class");
}
else
{
System.out.println("clObj and x are the references of two different classes");
System.out.println("clObj is a reference of " + clObj.getClass() + " and x is the reference of " + x.getClass());
}*/
clObj = y.getClass();
System.out.println("Y is object of type : " + clObj.getName()); // LINE C
clObj = clObj.getSuperclass();
System.out.println("Y's Superclass is " + clObj.getName()); // LILNE D
}
}
class X
{
int a;
float b;
}
class Y extends X
{
double c;
}
OUTPUTX is object of class : class java.lang.Class
Y is object of type : Y
Y's Superclass is X
DESCRIPTIONIn the above program we have demonstrated the usage of methods getClass
, getName
and getSuperClass
of java.langa.Class
. Firstly we have created two objects one for class X
and other for class Y
. At LINE A
we have created a reference clObj
of class java.lang.Class
and referenced it to java.lang.Class
using getClass()
and we have printed it at LINE B
and at LINE C
we are printing the class name of the clObj
reference. At LINE D
we are referencing clObj
to X
by using getSuperclass
method. and printed it.
THINGS TO TRY
- After
LINE B
uncomment the code and see the output.
The output will be clObj and x are the references of two different classes
clObj is a reference of class java.lang.Class and x is the reference of class com.java.lang.X