One problem -- and there are unfortunately several -- is that the subclasses declare their own variables with the same names as the ones in the base class. The toString() methods in the subclass will see these variables, not the ones in the parent -- but the ones in the subclasses are never initialized; only the ones in the parent class have values. That's why the subclass methods print 0's and nulls.
One way to fix:
1) Remove the duplicate variable declarations in the child classes
2) Make the variables in the parent class protected rather than private so the child classes can see them.
David Laverdy wrote:When I change it the output becomes 0NullBSCS. So somewhere it's not seeing the ID or his name.
It's doing exactly what you told it to do. If it's not clear why it's behaving in that particular manner, showing your current code--or an SSCCE that produces equivalent results--is the best way to get people to understand what you're talking about.
I would suggest keeping the fields all private, and including an overridden toString() method in the superclass. Then you can write this sort of method in the subclassOf course, if you can avoid creating new fields, so much the better. You simply use the superclass’ toString() method and don’t need to bother with that overriding.
Joined: Jun 30, 2003
I am guilty of answering the specific question/problem and not performing a good code review of the other aspects. I will chime in on the comments about the various variables and so forth, especially given how the classes are structured.
Looking at the various subclasses, of course I missed the obvious point that the subclasses should be using the parent class to store the inherited attributes. The code is part way there in that the common attributes are passed to the parent in the constructor but then also defined locally which fouls up a local reference. As mentioned, remove local variables and make parent class declarations protected or even better in my opinion consider adding getXXX methods to retrieve the values (and optionally setXXX if you want to be able to change them). While the toString is functional for the example, it likely would not be the sole way of accessing the data of an object.
Joined: Oct 13, 2005
I would also recommend not creating constructors you don’t want. If you don’t want a student with no name, you don’t want those no-arguments constructors. Delete them.