java - Overriding methods and threads -
iam having bit of problem question have been asked complete following class.
public class updowntrack extends opentrack { //alloweddirection attribute required private traindirection alloweddir; //add constructor set initial state down public updowntrack() { alloweddir = down; } //override usetrack method 1 train @ time //can use track public synchronized void usetrack(traindirection traindir, int id) { try { entertrack(traindir, id); traverse(); exittrack(traindir,id); } catch(exception e) { system.out.println("error" + e); } } // override entertrack method so,a train going in opposite // direction allowed enter track //then display train has entered track public synchronized void entertrack(traindirection traindir, int id) { if(alloweddir != traindir) { try { system.out.println("train " + id + " entered track, going " + traindir); } catch (exception e) { system.out.println(e); } } } //override exittrack method direction changed //before track exited //then display train has exited track public synchronized void exittrack(traindirection traindir, int id) { system.out.println(" train " + id + " left track, going " + traindir); traindir = (traindir == down)? down : up; notifyall(); } } methods overide opentrack class
public void usetrack(traindirection traindir, int id) { entertrack(traindir, id); traverse(); exittrack(traindir,id); } //this method doesn't check if safe traverse track. //it reports train has entered track. void entertrack(traindirection traindir, int id) { system.out.println("train " + id + " entered track, going " + traindir); } //this method reports train has left track void exittrack(traindirection traindir, int id) { system.out.println(" train " + id + " left track, going " + traindir); } } problem im getting wrong output, should get
train 1 enters track going train 1 leaves track train 3 enters track going down train 3 leaves track train 2 enters track going and on, im getting sequence , jumbled output
traindirection class of yours , when concatenate instance of string (such here: system.out.println(" train " + id + " left track, going " + traindir);), calls tostring method of class. default tostring(), inherited object returns object hashcode , not actual direction. need override public string tostring() method in class traindirection return useful information (such direction of train...)
Comments
Post a Comment