0
public A {

  public A(String arg0) {
  ...
  }

  public A(String arg0, String arg1) {
  ...
  }

}

public B extends A {

}

I would like B to automatically have the constructors inherited from A without having to implement them explicitly like:

public B(String arg0) {
    super(arg0);
}
public B(String arg0, String arg1) {
    super(arg0, arg1);
}

How can I achieve this?

4 Answers 4

8

You can't. Constructors are not inherited. Only the default one is automatically called on super classes, but still not "inherited".

The compiler will automatically add a call to the default constructor "super()" in every constructor, unless a constructor is explicitly called, and provided the superclass has a default constructor.

Moreover, if a classe doesn't explicitly define a constructor, the compiler will provide a default empty one, which as stated before calls the super() default constructor.

That's why it "looks like" the default constructor is "inherited", but it's just a compiler trick.

Sign up to request clarification or add additional context in comments.

1 Comment

If the superclass doesn't have a default constructor, the compiler will give error cause it can't insert the "super()" call, and require an explicit call to one of the non-default constructors. Or am i missing something?
3

From the Java Language Specification, section 8.8: Constructor declarations:

Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding.

Comments

2

you can't.As the Constructors can not be inherited in child classes.If we dont write any constructor in a class,a default one is provided.By using super keyword,we can call parent class constructor but with one condition i.e. it shud be the first statement in child constructor.

Comments

1

You can't. Constructors aren't inherited between classes, and every subclass constructor has to call a superclass constructor as its first operation (explicitly or implicitly).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.