With this code:
class SuperTest {
SuperTest() { whoAmI(); }
void whoAmI() { System.out.println(getClass().getName()); }
}
class Test extends SuperTest {
Test() { whoAmI(); }
}
new Test()
will print "Test"
twice. As a beginner I was expecting the output to be "SuperTest / Test"
. I understand now why this is not possible, and why the implicit this
will refer to child type only.
However I can't find what whoAmI()
should be to actually print the output SuperTest / Test
.
Said otherwise: how can whoAmI()
access the name of the type it is "called from"?
EDIT: I'm changing the title of the question for a new one which describes the problem better. (old was: Inheritance: Is there a "this-equivalent" construct to refer to super type from derived type).
This is the expected behavior, because in both cases getType()
is called on the same object of type Test
. This is because JVM knows the type of the object being created is of the derived class Test
at the time the base constructor is called, so that is the type being printed.
This behavior is not universal to all programming languages, but it works this way in Java.
If a class wants to access its own Class
object, it can do so statically, i.e. using the SuperTest.class
expression.
To get the behavior that you want you can pass the class to whoAmI
from the constructor, like this:
class SuperTest {
SuperTest() { whoAmI(SuperTest.class); }
void whoAmI(Class c) { System.out.println(c.getName()); }
}
class Test extends SuperTest {
Test() { whoAmI(Test.class); }
}
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