• Post Reply Bookmark Topic Watch Topic
  • New Topic

Extending a class; Must I explicitely call the super constructor?  RSS feed

 
Kentaro Shinbashi
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello.

I'm extending the JSlider class:
class MySlider extends JSlider{....}

I would like to do something like:
new MySlider(0, 10)

To make a slider from 0 to 10.

Aparently, the constructor JSlider(int, int) is not inherited automatically.

Do I have to make a constructor like:



Am I missing something?

Thanks.

Kentaro
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Constructors are never inherited.

If a subclass constructor does not have an explicit call to a constructor of its direct superclass, then an attempt is made to call a constructor from the direct superclass which has no parameter list.
[ June 24, 2006: Message edited by: Keith Lynn ]
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you subclass a class that does not have a no-argument constructor, you must also specify an explicit constructor of the subtype (with or without parameters). Let's look at a simpler example:

Class C meets the criteria above (does not have a no-argument constructor). Let's see what happens if you subclass it.

Compile-time error. Class T contains a default constructor, which, since it has no explicit call to super(...) or this(...), an explicit call to super() is made (this holds for all default constructors). Let's look at class T again, but with the implicit default constructor specified explicitly.

Note now that there is an explicit call to super(). The previous declaration of T also has this call, however, it is implicit. Note also that the constructor "super()" does not exist. Simply, there is not a no-argument constructor for type C (the superclass). This is why compilation fails. you should see an error message relating to the constructor invocation where the constructor does not exist.

The following declaration will pass compilation.

So will this declaration.

[ June 24, 2006: Message edited by: Tony Morris ]
 
Kentaro Shinbashi
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, Tony and Keith.

So, if I subclass JSlider, and I want to use all of the constructors of JSlider, then I must implement them all with super.

Thanks for your help.

Kentaro
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!