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?
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.
Related
I'm trying to build a base class with a method that needs to call a private method before and after performing the actual logic.
public abstract class Base {
public Base() {}
private void before() {
// doSomething
}
private void after() {
// doSomething
}
public void actual(Object object) {
before();
// doSomething
after();
}
}
public class SomeClass extends Base {
public SomeClass() {}
public void actual(Object object) {
// actual code that needs to be executed between before and after methods.
}
}
How would I go about this?
Create another method that can be overridden and implemented instead of overriding actual directly.
E.g.
public void actual(Object object) {
before();
doActual(object);
after();
}
protected abstract void doActual(Object object);
You could make the actual() method final if you want to ensure that nobody overrides it by mistake.
You can make the method as abstract e.g.
protected abstract void actual(Object object);
and create another public method which is going to be called
public void init(Object object){
before();
actual(object);
after();
}
If I don't want that a method on my class can be called, I just make it private.
But if I want to allow that method to be overridden, I have to make it protected
Is it possible to have a method on an abstract class that can't be called but can be overridden? (I guess not, but is there any workaround?)
Use case:
abstract class Super {
protected void finalize() {
}
public final void doThings() {
// do stuff
finalize();
}
}
and whoever wanted to extend the class:
class Sub extends Super {
#Override
protected void finalize() {
closeSockets();
alertSomeone();
}
}
But I don't want other classes calling mySub.finalize();
Instead of overwriting a method, the sub-class may provide the super-class with a Runnable which contains the code to be executed. You could do something like this:
public class Super {
private final Runnable subClassCode;
public Super(Runnable finalizeCode) {
subClassCode = finalizeCode;
}
public final void doThings() {
// do stuff
subClassCode.run();
}
}
public class Sub extends Super {
public Sub() {
super(() -> {
// code to be executed in doThings()
});
}
}
You dont need to set the Runnable instance in the constructor. You may also give access to a protected setFinalizeCode(Runnable) method but that method could also be called by other classes within the same package as Super.
In the following example, the call FirstChildclass first; first.someMethod(); will do the same as SecondChildclass second; second.someMethod();. Or am I wrong?
class Superclass {
public void someMethod() {
//do something
}
}
class FirstChildclass extends Superclass {
#Override
public void someMethod() {
super.someMethod();
}
public void someOtherMethod() {
//do something else
}
}
class SecondChildclass extends Superclass {
public void someOtherMethod() {
//do something else
}
}
Is there a reason why one will implement it like in FirstChildclass? Because I have seen many implementations like in FistChildclass and am wondering why anyone would do it.
If you ask about the difference between:
#Override
public returnType someName() {
return super.someName();
}
and not overriding it. There is no difference as well as there is no sense in doing it.
You should call super.someName() just in case you want to extend the original method.
Watch out! If you have a constructor you want to use in a child class, but you don't need any additional behavior, you'll call super(arguments).
This is about your design. Override means you wanna change the already existing implementation which is inherited from the parent.
If you are not doing anything different then you don;t want to do the
#Override
public void someMethod() {
super.someMethod();
}
That is useless.
#Override
public void someMethod() {
// do some other logic
super.someMethod();
// do some other logic
}
This is perfectly ok :) Because you are doing some tasks other than the parent's implementation.
I have an abstract method that implemented by other classes:
protected abstract void uninstallApp();
What I want to do is to force all the classes that must implement this method to use System.out.println() and another method: Log.report()
Is there any way that I can achieve this?
You could for example, do your logging stuff in the parent abstract class in a final method (so the child will not overwrite it). This class call a second method that the child classes should overwrite. Something like following:
protected final void uninstallApp(){
doUninstallApp();
Log.report();
}
protected abstract void doUninstallApp();
I agree with #Loic, we can go here for Command pattern...I tried to write the code below..May be It can help..
class Parent {
public final void uninstallApp() {
print();
doSomethingUsefull();
logReport();
}
//To be overriden as per requirement
protected void logReport() {
Log.report();
}
//To be overriden as per requirement
protected void print() {
System.out.println();
}
//To be overriden as per requirement
protected void doSomethingUsefull() {
//Implementation goes here
}
}
class Child extends Parent {
public void logReport() {
//Implementation goes here
}
public void print() {
//Implementation goes here
}
public void doSomethingUsefull() {
//Implementation goes here
}
}
class Main {
public static void main(String[] args) {
Parent p = new Child();
p.uninstallApp();
}
}
I have an interface called Worker which I want to expose so that the end-user can simply call:
Worker w = WorkerFactory.createInstance();
w.mainBit();
How can I prevent classes which extend my AbstractWorker class from providing their own implementation of the mainBit method?
This is the structure I have so far:
interface Worker {
void mainBit();
}
class WorkerFactory {
public static Worker createInstance() {
return new WorkerImpl();
}
}
abstract class AbstractWorker implements Worker {
#Override
public void mainBit() {
this.doThing1();
this.doThing2();
}
public abstract void doThing1();
public abstract void doThing2();
}
class WorkerImpl extends AbstractWorker {
#Override
public void doThing1() {
}
#Override
public void doThing2() {
}
#Override
public void mainBit() {
// I don't want classes to override this functionality
}
}
You can do that by making the method final.
Use the final keyword.
public final void mainbit ()
...
Mark the method as final, which prevents overriding:
public final void mainBit()
If you want to always use the AbstractWorker's mainBit, make it final in this class. This way, the subclasses won't override it.
Mark it final inside you abstract class (in Java). No other subclass will be allowed to override it.