42

How to inherit the constructor from a super class to a sub class?

devrys
  • 1,571
  • 3
  • 27
  • 43
Anil
  • 441
  • 1
  • 4
  • 3

6 Answers6

50

Constructors are not inherited, you must create a new, identically prototyped constructor in the subclass that maps to its matching constructor in the superclass.

Here is an example of how this works:

class Foo {
    Foo(String str) { }
}

class Bar extends Foo {
    Bar(String str) {
        // Here I am explicitly calling the superclass 
        // constructor - since constructors are not inherited
        // you must chain them like this.
        super(str);
    }
}
Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
  • 1
    Even as a non-n00b Java programmer, that's unclear to me. Could you clarify? – Matt Ball Feb 23 '10 at 16:27
  • @Bears will eat you: If the parent class has a constructor like this: `public Class(String arg1) { /* implementation here /* }` then the child class needs one like this: `public Subclass(String arg1) { super(arg1); }` – Powerlord Feb 23 '10 at 16:34
  • That sounds like a fancy way of saying "use `super` in the subclass' constructor." I have no idea what a constructor prototype is in Java. – Matt Ball Feb 23 '10 at 18:14
  • I believe that by "constructor prototype", Andrew is referring to the constructor signature. However, the answer is not necessarily true (or at least not very clear) -- you don't have to declare a constructor with the same signature, and there isn't much point to it since the client code would have to be referring to the new sub class anyways. If you want to call the underlying constructor, the user simply has to call super(/* parameter list */), supplying it whatever values it needs to for the parameters. (That was the point I was trying to make with my answer below, at least...) – MCory Feb 23 '10 at 22:37
  • How do you do this automatically in Eclipse? Eclipse can automatically write the super constructor definitions for you when you create a new class. But what about after you've made that class and forgot to check the box to tell Eclipse to do it? Is there some way? – trusktr Oct 24 '13 at 19:34
15

Superclass constructor CAN'T be inherited in extended class. Although it can be invoked in extended class constructor's with super() as the first statement.

ManishS
  • 627
  • 2
  • 11
  • 21
  • Yes...or you can invoke whichever variation of the superclass' constructor you want to use (it might have no arguments, as @GoodManish said, or it might have more). There are also situations in which `super();` will explicitly be called by the compiler before the rest of the body of any of your constructors is executed. – hotshot309 Nov 17 '12 at 04:01
7

Default constructors -- public constructors with out arguments (either declared or implied) -- are inherited by default. You can try the following code for an example of this:

public class CtorTest {
    public static void main(String[] args) {
        final Sub sub = new Sub();
        System.err.println("Finished.");
    }

    private static class Base {
        public Base() {
            System.err.println("In Base ctor");
        }
    }

    private static class Sub extends Base {
        public Sub() {
            System.err.println("In Sub ctor");
        }
    }
}

If you want to explicitly call a constructor from a super class, you need to do something like this:

public class Ctor2Test {
    public static void main(String[] args) {
        final Sub sub = new Sub();
        System.err.println("Finished.");
    }

    private static class Base {
        public Base() {
            System.err.println("In Base ctor");
        }

        public Base(final String toPrint) {
            System.err.println("In Base ctor.  To Print: " + toPrint);
        }
    }

    private static class Sub extends Base {
        public Sub() {
            super("Hello World!");
            System.err.println("In Sub ctor");
        }
    }
}

The only caveat is that the super() call must come as the first line of your constructor, else the compiler will get mad at you.

MCory
  • 437
  • 2
  • 13
  • 3
    Default constructors are not actually "inherited." If a public no-argument (A.K.A. default) constructor exists in the superclass and is not explicitly defined in the subclass, and if the subclass also does not have any explicitly defined overloaded constructors (that is, constructors with parameters), then the compiler will automatically insert into the subclass a public no-argument constructor containing only `super();`. This calls the superclass' default constructor. – hotshot309 Nov 17 '12 at 04:06
4

Read about the super keyword (Scroll down the Subclass Constructors). If I understand your question, you probably want to call a superclass constructor?

It is worth noting that the Java compiler will automatically put in a no-arg constructor call to the superclass if you do not explicitly invoke a superclass constructor.

RichardOD
  • 28,883
  • 9
  • 61
  • 81
1

Say if you have

/**
 * 
 */
public KKSSocket(final KKSApp app, final String name) {
    this.app = app;
    this.name = name;
    ...
}

then a sub-class named KKSUDPSocket extending KKSSocket could have:

/**
 * @param app
 * @param path
 * @param remoteAddr
 */
public KKSUDPSocket(KKSApp app, String path, KKSAddress remoteAddr) {
    super(app, path, remoteAddr);
}

and

/**
 * @param app
 * @param path
 */
public KKSUDPSocket(KKSApp app, String path) {
    super(app, path);
}

You simply pass the arguments up the constructor chain, like method calls to super classes, but using super(...) which references the super-class constructor and passes in the given args.

Chris Dennett
  • 22,412
  • 8
  • 58
  • 84
1

You inherit class attributes, not class constructors .This is how it goes :

If no constructor is added in the super class, if no then the compiler adds a no argument contructor. This default constructor is invoked implicitly whenever a new instance of the sub class is created . Here the sub class may or may not have constructor, all is ok .

if a constructor is provided in the super class, the compiler will see if it is a no arg constructor or a constructor with parameters.

if no args, then the compiler will invoke it for any sub class instanciation . Here also the sub class may or may not have constructor, all is ok .

if 1 or more contructors in the parent class have parameters and no args constructor is absent, then the subclass has to have at least 1 constructor where an implicit call for the parent class construct is made via super (parent_contractor params) .

this way you are sure that the inherited class attributes are always instanciated .

Java Main
  • 1,521
  • 14
  • 18
  • " the compiler will invoke it for any sub class instanciation" - it seems that the point above is that you have to explicitly invoke super() if your subclass have a no-arg constructor. – Vlad Feb 15 '18 at 22:49