abstract class can not provide constructor for sub class?

K

Kevin

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!
 
K

Kevin

PS: does this mean that, I can not use the constructor to provide some
operations for all the subclasses?
 
K

Kevin

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. :)
 
P

puzzlecracker

Kevin said:
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. :)

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 .
 
P

Patricia Shanahan

Kevin said:
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?

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top