Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .getclass() on an interface

Tags:

java

This is probably a very easy question. Hey I'm a student and relatively new to java and I'm currently studying for a midterm that I have tomorrow. One of the practice questions I am stuck on is what happens when you have something like:

System.out.println(interface1.getClass().getName());

interface1 has been declared as interface1 = class1. I'm pretty sure it would print "class1" and not "interface1" because interface1 is not a class right? but I'm not sure as the question also says that if it produces a compile time error then say so. Our professor is known for tricking us and more then once I get back a quiz and still been confused as to why I got a problem wrong.

like image 588
Erik Avatar asked Nov 01 '11 02:11

Erik


1 Answers

It's not because it's an interface that you'd get class1, but because getClass() will resolve to the runtime class of the instance. Since you've created it as a class1, that's the runtime type. Won't give you a compile-time error.

Getting a Class object for an interface is possible via reflection.

Alternatively you can access the class more directly through the class keyword:

String className = Runnable.class.getName();
like image 78
G_H Avatar answered Nov 18 '22 13:11

G_H