For starters, I hope I have worded the question well enough. If not, please feel free to edit it or suggest changes.
I’m working through a Java textbook to help with my university course and I came across an exercise asking me to create an abstract class Airplane, with three subclasses, B747, B757 and B767. Each object of those three subclasses has a unique serial number.
Cutting out a lot of the other parts of the question (which I hope aren’t relevant!), I did this:
public abstract class Airplane {
String serialNumber;
public String toString() {
return getClass().getName() + ": " + serialNumber
}
}
I then declared three subclasses, each of which looked like this:
public class B747 extends Airplane {
B747(String serial) {
serialNumber = serial;
}
}
Finally, in my main program, I instantiated new objects using the following code:
Airplane a = new B747("ABC101");
System.out.println ("Airplane a: " + a);
Now, the code works fine. However, when I looked at the answers in the book, they chose to do it a different way. They instantiated each object in the same way, but instead in each class had the following method:
public B747 (String serial) {
super (serial);
}
In the abstract superclass Airplane, they then had:
public Airplane (String serial) {
this.serial = serial;
}
Was this just a matter of personal preference, to elevate the String to the superclass and act on it there, or does this provide any benefits, whether security or otherwise?
It’s only changing where the variable is accessed – not where it’s declared. And it’s a good thing:
Aeroplaneshould have a serial number, so it makes sense for theAeroplaneclass to enforce thatprivate(andfinal) withinAeroplane, with a “getter” to provide read-only access to it as widely as is requiredBoth parts are important – but if you’re not sure about the first aspect, consider what would happen if you had another few subclasses. Do you really want the assignment to occur in every single subclass? There will always be a superconstructor call – whether implicit or explicit – but there’s no reason to repeat the assignment.
I definitely prefer the book’s solution to your one – particularly if they make the field
privateandfinal. In my code, I hardly ever use non-private fields, other than for constants.