-2

I have tried to execute the given code given below:

public class XXX
{
public static void main(String[] args)
{System.out.println(new XXX().class);
}
}

But the code shows an error during compilation:

/XXX.java:4: error: <identifier> expected
{System.out.println(new XXX().class);
                              ^
/XXX.java:4: error: ';' expected
{System.out.println(new XXX().class);
                                   ^
2 errors

But when I compile the following code:

public class XXX
{
public static void main(String[] args)
{System.out.println(XXX.class);
}
}

it works fine,I mean it prints the output as given below

class XXX

Does this mean that the ".class" operation( I don't know what to call it) in java is only meant for a class and not its instances ?

Deep Roy
  • 89
  • 10

1 Answers1

2

For instances you have to use the method getClass()

public class XXX
{
   public static void main(String[] args)
      {System.out.println(new XXX().getClass());
   }
}
Jens
  • 67,715
  • 15
  • 98
  • 113
  • but does that mean that ".class" is statically accessed, if so then why can't they be accessed by instances of the class....consider the code below : class enthrian{ – Deep Roy Nov 23 '17 at 09:32