| Author |
public constructor in an abstract class.
|
Sudhakar Sharma
Ranch Hand
Joined: Apr 04, 2009
Posts: 71
|
|
|
Why there can be public constructor inside an abstract class, what is the scenario to use this public constructor? Please elaborate.
|
 |
Seetharaman Venkatasamy
Ranch Hand
Joined: Jan 28, 2008
Posts: 5575
|
|
|
new Sub() constructor have to call super()[imagine it is an abstract], if both are in different packages
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3865
|
|
You can safely make it protected, though, since only subclasses will ever be calling the constructor.
This is speculation - I don't know what the designers had in mind - but here's one reason that might explain it. If you don't provide a constructor, then a no-arg constructor is added for you by the compiler. And this has the same accessibility as the class. So if you have a public abstract class with no explicit constructor, then the implicit one is public. And this needs to be allowed.
They could have changed the rules so that instead the implicit constructor was protected if the class was abstract. They picked the other option.
|
 |
Seetharaman Venkatasamy
Ranch Hand
Joined: Jan 28, 2008
Posts: 5575
|
|
Matthew Brown wrote:You can safely make it protected, though, since only subclasses will ever be calling the constructor.
Indeed, never thought of it.
|
 |
Rahul M Mishra
Greenhorn
Joined: Jul 02, 2012
Posts: 10
|
|
Think about this - what is abstract class does not have constuctor that is accessible to sub-class? Sub-class won't be able to inherit from Abstract class (compilation error)
So Abstract class must have accessible constructor. This could be public (if sub-class is in different package), protected or package scope
Also it is implied that if you make default constructor (with no-arg) private in abstract class, you need to have at least one constructor with arg/s and sub-class need to call it using super(arg/s)
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32833
|
|
|
Don’t call a no-args constructor default. A default constructor is one written by the compiler, because no other constructor is provided.
|
 |
Rahul M Mishra
Greenhorn
Joined: Jul 02, 2012
Posts: 10
|
|
Campbell Ritchie wrote:Don’t call a no-args constructor default. A default constructor is one written by the compiler, because no other constructor is provided.
You are right, thanks!
|
 |
 |
|
|
subject: public constructor in an abstract class.
|
|
|