Re: Inconvenience due to abstract class does not have a constructor
www wrote:
I have an Abstract class and other classes which are subclasses of it.
public abstract MyClass {
protected List _list;
You should not expose implementation details to subclasses. Make this
variable private.
Don't use underscores in names for non-constant (i.e., non-final or mutable)
variablea.
Instance variables should be initialized in the declaring class. You cannot
count on a subclass implementor to do this correctly.
public abstract void doIt();
}
public class ClassA extends MyClass {
public ClassA() {
_list = new ArrayList(); //this is mandatory since _list is not
implemented YET!
...//other things
}
public void doIt() {
double d = getList().get(1); //using super_list
You do not show a getList() method. Where does this come from?
}
..
}
It is kind of hard or tricky for anybody to remember, if you extend your
class from MyClass, be sure to add "_list = new ArrayList()". Actually,
I didn't know such a "requirement" and got null point exception when I
ran my program.
Not only is it not a requirement, it's terrible coding to set things up where
an instance variable is instantiated only by a subclass.
The point of an abstract class is to fix certain aspects of the
implementation. There is no such thing as an "abstract instance variable".
Should I do like this:
public abstract MyClass {
protected List _list = new ArralyList(); //now, the subclass no need
to implement it in their constructors
They should *never* need to implement a superclass variable.
public abstract void doIt();
}
Yes.
--
Lew