1

i have a problem with my abstract class not knowing, which subclass calls its constructor.

abstract class A {

    Field field;

    public A() {
        this.field = Manager.add(Here i would like to add the type of subclass);
    }
}

I could carry the class-type as a parameter in a chain of constructors, but i was wondering if there is a different way.
Maybe I could use the StackTrace to find out about the subclasses and get their type, but i don't think it should be used this way.

Thank you very much in advance for your answers :)

  • 4
    Usually, the abstract class should not need to know about this. Type specific logic should happen in the subclass. Note that you can define an abstract method in the abstract class, call it from the constructor but implement it in the subclasses. So you can somehow influence the behaviour of the superclass constructor. – J Fabian Meier Sep 02 '16 at 11:47
  • http://stackoverflow.com/questions/3417879/getting-the-name-of-a-sub-class-from-within-a-super-class – Arnav Borborah Sep 02 '16 at 11:48
  • 2
    @JFMeier, calling an abstract method from the constructor is discouraged since the method could access uninitialized properties. – Codebender Sep 02 '16 at 11:52
  • @Codebender I know this is risky (I ran into the problem you mentioned once myself), but there might be situations in which it is useful. – J Fabian Meier Sep 02 '16 at 11:55

1 Answers1

4

this.getClass() wil give you class that was instantiated.

talex
  • 17,973
  • 3
  • 29
  • 66
  • Is it possible to call `this.getClass()` before calling the constructor of the super class? – Schokokuchen Bäcker Sep 02 '16 at 11:56
  • No, because a subclass is instantiated after its base/super class. – dsp_user Sep 02 '16 at 11:57
  • @SchokokuchenBäcker you can't do *anything* before calling the constructor of the super class. The `super(...)` call has to come first in a constructor. – Andy Turner Sep 02 '16 at 11:57
  • @SchokokuchenBäcker yes. There is a trick to do this. But you better to ask separate question about it. – talex Sep 02 '16 at 11:59
  • @talex how do you think you can do this? I'm pretty sure you can't. (If you're thinking of using an field initializer, this is executed after the call to the super ctor). – Andy Turner Sep 02 '16 at 12:09
  • @AndyTurner I show you magic :) `super(myMethodThatwillBeInvokedBeforeSuperConstructor())`. This method have constraints and you should not do this for many reason, but it works. – talex Sep 02 '16 at 12:12
  • 1
    `myMethodThatwillBeInvokedBeforeSuperConstructor()` has to be static, though, so you can't call `this.getClass()` in there. You'd get a "cannot reference this before supertype constructor has been called" error (at least in Java 8). – Andy Turner Sep 02 '16 at 12:12