java abstract methode call all in subclasses - java

I would like to call an abstract method in each subclass. Here is an example:
public abstract class ControllerAbs implements UiListener
/**
* implements from ui listener. when it's called, then must the ui be updated
*/
#Override
public synchronized void Update() {
// for change ui elements from another no fx-thread
// see http://stackoverflow.com/questions/21674152/timer-error-java-lang-illegalstateexception
Platform.runLater(new Runnable() {
#Override
public void run() {
UiUpdate();
}
});
}
/**
* update ui in subcontroller
*/
protected abstract void UiUpdate();
}
Now, I extend my subclass with the abstract method:
#Override
protected void UiUpdate() {
// update ui
}
But when I have more than one subclass that will extend from controllerabs, only the first subclass will be updated. What is wrong?
I want a method that will be called in each subclass.
Best regards,
sandro

Use the keyword super in order to call the method for the supclass defined. E.g. something like the following:
public class SubClass1 extends ControllerAbs {
#Override
protected void UiUpdate() {
// Update for Subclass 1
}
}
public class SubClass2 extends SubClass1 {
#Override
protected void UiUpdate() {
// Update for Subclass 2
super.UiUpdate(); // update in the upper subclass
}
}
Using this keyword, you can refer to the object that is higher in the hierarchy and call its implementation of the method.

I create a static list of controllers
by create a new controller or subcontroller add it to the list.
public class ControllerAbs() implements UiListener {
private static ArrayList<ControllerAbs> controllers;
// code
protected registerUiUpdateListener(ControllerAbs controller) {
controllers.add(controller);
}
/**
* implements from ui listener. when it's called, then must the ui be updated
*/
#Override
public synchronized void Update() {
// for change ui elements from another no fx-thread
// see http://stackoverflow.com/questions/21674152/timer-error-java-lang-illegalstateexception
Platform.runLater(new Runnable() {
#Override
public void run() {
for (ControllerAbs controller : controllers) {
controller.uiUpdate(); // update ui in controller
}
});
}
/**
* update ui in subcontroller
*/
protected abstract void uiUpdate();
}
public class SubClass1 extends ControllerAbs {
public SubClass1() {
registerUiUpdateListener(this); // add to list
}
#Override
protected void uiUpdate() {
// lblTest.setText(testVariable);
}
}
public class SubClass2 extends ControllerAbs {
public SubClass2() {
registerUiUpdateListener(this); // add to list
}
#Override
protected void uiUpdate() {
// lblTest.setText(testVariable);
}
}

Related

How can I override methods?

I'm trying to override the methods init(), render() and release(), but can't get it to work. I've looked at tutorials on overriding and have checked the following:
Overriding of methods takes place inside the subclass of the original methods
The method names are the exact same
The parameters are the same (none in this case)
I have 2 classes:
public class Game {
public void run() {
System.out.println("Running!");
init();
render();
release();
}
public void init() {}
public void render() {}
public void release() {}
}
and
public class Loader extends Game {
#Override
public void init() {
System.out.println("Initializing");
}
#Override
public void render() {
System.out.println("Rendering");
}
#Override
public void release() {
System.out.println("Releasing.");
}
}
Why is the only thing printed to the console "Running!"?
You have to use run() method from overriding class Loader object and not from Game object to get desired result.
You have to override the Game#run function by creating a method in the subclass with the #Override annotation.
public class Loader extends Game {
#Override
public void run() {
System.out.println("Running from Loader!");
}
}
When you define the Game object you have to instantiate a new Loader object.
Game game = new Loader();
game.run(); // this object is an instance of Loader so Loader#run() is called.

Template Method calling super and use implementation

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.

Calling super Method within Anonymous Class

What is the proper way to call the super method of ParentClass from an anonymous class?
In its current state super is referring to the Runnable.
public class ChildClass extends ParentClass {
#Override
public void myMethod(final double value) {
new Runnable() {
#Override
public void run() {
super.myMethod(value);
}
};
}
}
You can use the following code:
public class ChildClass extends ParentClass {
#Override
public void myMethod(final double value) {
new Runnable() {
#Override
public void run() {
ChildClass.super.myMethod(value);
}
};
}
}
call ChildClass.super.myMethod(value);
Note : You can also use ChildClass.this.myAttribute / ChildClass.this.myMethod() if you want to access instance attributes/methods from ChildClass.

java - ensuring that method will be called at the end of child class construction

I've got abstract class :
public abstract class MyComposite extends Composite {
protected abstract void initHandlers();
}
And a buch of classes which extends it. How to ensure that method initHandlers() is going to be called at the end of child classes construction? Example child class:
public CollWidget extends MyComposite {
public CollWidget() {
/** Some stuff thats need to be done in this particular case */
initHandlers(); // This method should be invoked transparently
}
#Override
public void initHandlers() {
/** Handlers initialisation, using some components initialized in constructor */
}
}
There is no way to do it automatically, since the parent constructor is always called before the child one (explicitely or implicitely).
One solution workaround could be:
public abstract class MyComposite {
public MyComposite() {
construct();
initHandlers();
}
protected abstract void construct();
protected abstract void initHandlers();
}
public class CollWidget extends MyComposite {
#Override
protected void construct() {
// called firstly
}
#Override
public void initHandlers() {
// called secondly
}
}

Make sure method is executed, even if overriden

Let's say I have an interface with some methods, like this:
interface Task {
void before();
void doStuff();
void after();
}
Here I would implement part of it:
abstract class PoliteTask implements Task{
#Override
public void before() {
System.out.println("Hey");
}
#Override
public abstract void doStuff();
#Override
public void after() {
System.out.println("Cya");
}
}
Now I want to make sure that those before() and after() implementations are called in all extending classes.
Here we have a class that needs to init something in before():
class ActualStuffTask extends PoliteTask {
private int fancyNumber;
#Override
public void before() {
// init some things
fancyNumber = 42;
}
#Override
public void doStuff() {
System.out.println("Look, a number: "+fancyNumber);
}
}
Obviously, ActualStuffTask overrides before(), hence it does not say "Hey", only "Cya".
If I made the methods in PoliteTask final, this wouldn't happen, but then it's child classes could not override the methods.
Calling super.before() in the ActualStuffTask would work, but I want to have this effect guaranteed, regardless of child class implementation.
The question is:
What pattern should I use to have both parent implementation, and child implementation?
I like to use abstract methods which you implement in the implementation classes.
abstract class PoliteTask implements Task{
#Override
public final void before() {
System.out.println("Hey");
doBefore();
}
protected abstract void doBefore();
protected abstract void doAfter();
#Override
public abstract void doStuff();
#Override
public final void after() {
System.out.println("Cya");
doAfter();
}
}
class ActualStuffTask extends PoliteTask {
private int fancyNumber;
#Override
protected void doBefore() {
// init some things
fancyNumber = 42;
}
#Override
public void doStuff() {
System.out.println("Look, a number: "+fancyNumber);
}
#Override
protected void doAfter() {
// something else
}
}
Notice that the Task methods are final. They don't need to be. It depends how you are building your API.
The usual approach for such case is like this (simplified example):
abstract class Base {
public final void before() {
System.out.println("Hey");
doBefore();
}
protected void doBefore() {
}
}
This way base code always will get executed, and subclasses can add their implementation.
You can follow the template method pattern. Create a final method in AbstractClass (say, doAll), that calls the other methods in order:
public final void doAll() {
before();
doStuff();
after();
}
Then you can have before and after also be final methods, so that they will always be executed by subclasses, and their behavior can't be changed.
One option is to call super.before() in your ActualStuffTask class explicitly:
#Override
public void before() {
super.before();
// init some things
fancyNumber = 42;
}
Another option is to change design of you parent class and "protect" before method with final keyword:
abstract class PoliteTask implements Task {
#Override
public final void before() {
System.out.println("Hey");
internalBefore();
}
protected abstract void internalBefore(); // child class should override this method
...
}

Categories