Reputation: 609
I have implemented Template Method, and i faced with this situation:
public class ProductTemplate() {
protected Item getItemFromShop(){
processItemPrice();
callOrderSummary();
}
protected void processItemPrice() {
Do some logic....
}
protected void callOrderSummary()
Do some logic....
}
}
public class ImportedProduct extends ProductTemplate() {
@Override
protected Item getItemFromShop() {
super.getItemFromShop(); // When i call this super method, they will use the processItemPrice() from the implementation
}
@Override
protected void processItemPrice() {
Do another logic....
}
}
My doubt is.. can in call an super method and if inside this super method there is a method call and i have this method overridden, what method implementation the class will use?
Solution: OK It's works fine. but when i have one class that calls one single method overridden, is it useless have this:
public class SimpleProduct extends ProductTemplate(){
public processItemPrice(){
super.processItemPrice()
}
}
This ProductTemplate implements an interface, and is used within Strategy pattern.. is it right?
Upvotes: 1
Views: 374
Reputation: 41137
The easiest way to understand this sort of thing is to code debugging prints into your code and see what happens.
Cleaning up your code (so it compiles) and adding some prints:
public class ProductTemplate {
protected Item getItemFromShop() {
processItemPrice();
callOrderSummary();
return null;
}
protected void processItemPrice() {
// Do some logic....
System.out.println("ProductTemplate.processItemPrice()");
}
protected void callOrderSummary() {
// Do some logic....
System.out.println("ProductTemplate.callOrderSummary()");
}
}
public class ImportedProduct extends ProductTemplate {
@Override
protected Item getItemFromShop() {
return super.getItemFromShop(); // When i call this super method, they will use the processItemPrice() from the implementation
}
@Override
protected void processItemPrice() {
// Do another logic....
System.out.println("ImportedProduct.processItemPrice()");
}
public static void main(String[] args) {
new ImportedProduct().getItemFromShop();
}
}
If you run the ImportedProduct
class (which is now possible because I added a main
method), you'll get the output:
ImportedProduct.processItemPrice()
ProductTemplate.callOrderSummary()
showing that the overridden method in your subclass is indeed called.
Note: There's no need to override the getItemFromShop
method as you do. It does nothing different from the overridden method.
Upvotes: 2