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 becausegetClass()will resolve to the runtime class of the instance. Since you’ve created it as aclass1, that’s the runtime type. Won’t give you a compile-time error.Getting a
Classobject for an interface is possible via reflection.Alternatively you can access the class more directly through the
classkeyword: