Reputation:
I have a method set in my superclass...
public void explain() {
for (Item item: Instances) {
System.out.println(item.getname + " is in location " + item.place):
}
}
I need to override this same method in the subclass to print out the original output message but the new instance for this method needs to print out different values that have been set in the subclass
I'm confused with the overriding bit (as I know little about it) and would like an explanation.
Upvotes: 2
Views: 166
Reputation: 27496
So just give the method in base class parameter like
public void explain(Instances i)
and call it in your subclass. You don't need to override anything and have the benefit of code reuse from the base class. Or, in case some more complicated logic you can try Template method pattern like
Base class
public abstract class Base {
public abstract explain(Instances i);
public void print(Item i) {
//do something
}
}
Subclass
public class Subclass extends Base {
@Override
public void explain(Instance instances) {
//do some logic and call print in loop
print(someItemfromInstances);
}
}
Upvotes: 2
Reputation: 11881
In your subclass:
@override //Throw a warning if you're not overidding anything
public void explain(){
super.explain();//This will call the method from the superclass.
//Do what you have to do in the sub-class
}
Upvotes: 0