Is it good practice to let abstract classes define instance variables?
public abstract class ExternalScript extends Script {
String source;
public abstract void setSource(String file);
public abstract String getSource();
}
The sub class, ExternalJavaScript.class, would then automatically get the source variable but I feel it's easier to read the code if all the sub classes themselves define the source, instead of from inheritance.
What is your advice?
/Adam
I would have thought that something like this would be much better, since you're adding a variable, so why not restrict access and make it cleaner? Your getter/setters should do what they say on the tin.
Bringing this back to the question, do you ever bother looking at where the getter/setter code is when reading it? If they all do getting and setting then you don't need to worry about what the function 'does' when reading the code. There are a few other reasons to think about too:
Always think whether your class is really a different thing or not, and that should help decide whether you need anything more.
Of course. The whole idea of abstract classes is that they can contain some behaviour or data which you require all sub-classes to contain. Think of the simple example of WheeledVehicle - it should have a numWheels member variable. You want all sub classes to have this variable. Remember that abstract classes are a very useful feature when developing APIs, as they can ensure that people who extend your API won't break it.
Sure.. Why not?
Abstract base classes are just a convenience to house behavior and data common to 2 or more classes in a single place for efficiency of storage and maintenance. Its an implementation detail.
Take care however that you are not using an abstract base class where you should be using an interface. Refer to Interface vs Base class