7

I have simple three classes:

class A {
  public A(int a){ }
}

class B extends A {
  public B(int b){ super(b); }
}

class C extends B {
  public C(int c){ super(c); }
}

So, the order of execution during class instancing is C->B->A->B->C and all objects are instantiated correctly. Then, the question:

CAN I in some way write a constructor for C class like this:

  public C(int c){
    super.super(c);
  }

The idea is to call the constructor from A class, not from immediate parent B. Is this possible?

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
piotao
  • 267
  • 3
  • 12
  • 2
    Well, there are no methods being overridden here, so just call `A(c)`. (I'm assuming this is a typo though - please fix your code to actually illustrate your problem). – Andy Turner Nov 04 '16 at 10:43
  • 2
    The code won't even compile at the moment, because you're not declaring constructors - you're declaring methods with names the same as the classes. – Jon Skeet Nov 04 '16 at 10:44
  • 1
    A is meant to be the constructor, I guess. OP maybe should think about his architecture, though. – Jeremy Nov 04 '16 at 10:44
  • possible duplicate [question](http://stackoverflow.com/questions/11935895/java-how-to-call-super-super-in-overriden-method-grandparent-method) and [another](http://stackoverflow.com/questions/586363/why-is-super-super-method-not-allowed-in-java) – Karthik Nov 04 '16 at 10:46
  • 1
    Inheritance is unconditional, so do not extend if you don't actually want the "B" part every time. Make a class that extends directly from A, and in case it should have something in common with the others that isn't inherited directly put that into a common `interface`. Not being able to skip a class is not a limitation, it's a design issue on your side. – zapl Nov 04 '16 at 11:12
  • Thank you. In fact I redesigned the code and constructors are OK and I have no more problems with them. However, I have a very similar issue in this simple class hierarchy: in class A, B, and C I have a "makeStr" function, which is creating some string. In B.makeStr I am calling super.makeStr from class A, but in class C, I can't call super.super.makeStr from A, omitting class B. How to overcome this limitation? – piotao Nov 06 '16 at 21:52

1 Answers1

11

No you can't do that.

All classes in a heirarchy need to be constructed. You cannot bypass the construction of B.

What you could do is write a protected constructor in B that's essentially a no-op, and call that from the constructor in C.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483