Topics Index

class - Java Example Program

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");
            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;


X is object of class : class java.lang.Class
Y is object of type : Y
Y's Superclass is  X


In 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.

  • 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
  • Try for the belwo code.
    Integer i = 10;
    The output should be class java.lang.Integer
    Remember primitive Java types ( boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.

© meritcampus 2019

All Rights Reserved.

Open In App