abstract class A
{
public A()
{
}
public A(int i, int j)
{
}
}
public class B extends A
{
}
B does not have the corrresponding constractor of B(int i, int j) from
A, though B may have all other fucntions of A.
That's to say:
B b = new B(10, 14); will not work.
Isn't it strange?
I found the behavior of constractors are pretty different from normal
functions. How to explain it?
Thanks!
Kevin - 24 Jul 2006 03:47 GMT
PS: does this mean that, I can not use the constructor to provide some
operations for all the subclasses?
Kevin - 24 Jul 2006 04:05 GMT
Well, my purpose is to make sure all the subclasses will have one
uniform constructor (which takes certain parameters). How can I do
that?
Thanks. :-)
> PS: does this mean that, I can not use the constructor to provide some
> operations for all the subclasses?
puzzlecracker - 24 Jul 2006 04:12 GMT
> Well, my purpose is to make sure all the subclasses will have one
> uniform constructor (which takes certain parameters). How can I do
[quoted text clipped - 4 lines]
> > PS: does this mean that, I can not use the constructor to provide some
> > operations for all the subclasses?
Kevin,
In Java, just like in C++, constructors are not typical functions.
One of the differences is that constructors are not inherited by
subclasses. You can confirm that by trying to use c'tors from
non-abstract superclass not define in the subclass .
Patricia Shanahan - 24 Jul 2006 04:46 GMT
> abstract class A
> {
[quoted text clipped - 20 lines]
> I found the behavior of constractors are pretty different from normal
> functions. How to explain it?
Perhaps it is because constructors are not methods?
Constructors are not inherited. However, a subclass constructor can be
very short and simple:
public B(int i, int j){
super(i,j);
}
If you want to ensure that every subclass has a constructor that deals
with i and j, get rid of the parameterless new A() constructor. It
implies that
public B(){
super();
}
would be a valid B constructor, and that is what the compiler makes up
as default constructor if B does not specify at least one.
Patricia