Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to inherit Constructor from super class to sub class

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

like image 354
Anil Avatar asked Feb 23 '10 16:02

Anil


People also ask

How do you call a super class constructor in a subclass?

To explicitly call the superclass constructor from the subclass constructor, we use super() . It's a special form of the super keyword. super() can be used only inside the subclass constructor and must be the first statement.

Can you call a sub class constructor from super class constructor?

To call the constructor for each superclass within the subclass constructor, use the following syntax: obj@SuperClass1(args,...); ... obj@SuperclassN(args,...);

Can constructor be inherited through a subclass that calls the superclass constructor?

Constructors are not inherited. The superclass constructor can be called from the first line of a subclass constructor by using the keyword super and passing appropriate parameters to set the private instance variables of the superclass.

Can I cast super class to subclass?

You can try to convert the super class variable to the sub class type by simply using the cast operator. But, first of all you need to create the super class reference using the sub class object and then, convert this (super) reference type to sub class type using the cast operator.


2 Answers

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);     } } 
like image 101
Andrew Hare Avatar answered Sep 17 '22 14:09

Andrew Hare


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.

like image 25
ManishS Avatar answered Sep 16 '22 14:09

ManishS