Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance: Is there a way to discover the class a method was called from?

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).

like image 980
mins Avatar asked Jul 19 '14 23:07

mins


1 Answers

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); }        
}
like image 136
Sergey Kalinichenko Avatar answered Nov 04 '22 16:11

Sergey Kalinichenko