Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Private Constructor & Subclassing  RSS feed

 
Joseph Sweet
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Everyone:

I am wondering why it is illegal to extend a class whose default constructor is defined to be private.

Any ideas?

Thanks.
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Joseph Sweet:
Hello Everyone:

I am wondering why it is illegal to extend a class whose default constructor is defined to be private.

Any ideas?

Thanks.


If you are going to subclass another class, you must use a non-private constructor. If the default (no-arg) constructor is private, then you are supposed to use a constructor that isn't private.

As for why? Because the compiler is enforcing the requirement requested by the developer of the base class -- if the developer of the base class wanted you to use that particular constructor for subclassing, he/she would have made that constructor (at least) protected.

Henry
[ October 01, 2007: Message edited by: Henry Wong ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember that when an object is instantiated, a constructor for each class in its hierarchy up through Object is called.

So a subclass must be able to call a superclass constructor, and a private constructor cannot be called from another class.
 
Joseph Sweet
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you now I got it
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!