Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implictly call parent class's constructor

I want to do following thing:

class P {
  P(int a) {
    // construct
  }
}

class C extends P {
}

// in main
int a = 2;
C foo = new C(a); // can I do this?

I want create child object C by calling parent class P's constructor without writing any constructor in class C like "super(a)". Is that possible?

The idea is that I have a lot of class like "class C" which needs the same constructor functionality as "class P". So I don't want write a constructor method each time I create a new similar class.

Thanks

like image 232
Linghua Jin Avatar asked Aug 26 '13 03:08

Linghua Jin


1 Answers

  • A constructor implicitly calls the parameter-less constructor of it's immediate super class(only if there's no explicit call)
  • When you define your own constructor,the default constructor would not be created.

So,in your case Class C has a default constructor which would try to implicitly call the default constructor of Class P which doesn't exits and would fail.

So,you have to do it this way

class P 
{
    public P(int a) 
    {
    // construct
    }
}

class C extends P 
{
    public C(int x)
    {
       super(x);
    }
}
like image 67
Anirudha Avatar answered Nov 05 '22 02:11

Anirudha