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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With