How can I override methods? - java

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.

Related

How to create a java method on a base class that calls other methods?

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();
}

java abstract methode call all in subclasses

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);
}
}

Why is the constructor of a class which implements Runnable Interface not called?

I tried using the constructor of a class which implements Runnable Interface. But I was surprised to see it was never called. The run() method was called, however, the constructor was never called. I have written a simple sample code to show the phenomenon. Can anyone explain why this is happening?
public class MyRunner implements Runnable {
public void MyRunner() {
System.out.print("Hi I am in the constructor of MyRunner");
}
#Override
public void run() {
System.out.println("I am in the Run method of MyRunner");
}
public static void main(String[] args){
System.out.println("The main thread has started");
Thread t = new Thread(new MyRunner());
t.start();
}
}
Change public void MyRunner() to public MyRunner() (no return type). public void MyRunner() is not a constructor, it's a method. Constructor declarations don't have a return type.
You have a default Constructor there, since you don't define any constructor. And, the default Constructor was called internally.
A Constructor can't have return type. In your case, public void MyRunner() {} is a method. remove void from you Constructor signature.
Constructor is a special method which does not have return type and its name is same as Class name so remove void from method name to make it constructor.
public class MyRunner implements Runnable {
public MyRunner() {
System.out.print("Hi I am in the constructor of MyRunner");
}
#Override
public void run() {
System.out.println("I am in the Run method of MyRunner");
}
public static void main(String[] args) {
System.out.println("The main thread has started");
Thread t = new Thread(new MyRunner());
t.start();
}
}
This will work and your constructor will be called.

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
...
}

Instance fields don't initialize if overridden base method is called during class initialization

There's a base class ServerAdapter:
public abstract class ServerAdapter {
public ServerAdapter() {
initGUI();
}
protected abstract void initGUI();
}
And a child class that inherits ServerAdapter:
public abstract class LinuxServerAdapter extends ServerAdapter {
protected CheckBox key = new CheckBox();
public LinuxServerAdapter() {
super();
}
#Override
public void initGUI() {
//NPE is thrown here, because key = null
key.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
//Something happens here
}
});
}
}
End class that inherits LinuxServerAdapter:
public class MyLinuxServerAdapter extends LinuxServerAdapter {
public MyLinuxServerAdapter() {
super();
}
public static void main(String args[]) {
ServerAdapter server = new MyLinuxServerAdapter();
}
}
NPE is thrown when I try to add clickHandler on a key.
Why key isn't initialized? Is this a case where initialization order works in a specific way?
Just initialize in the init method. That's the purpose after all..
#Override
public void initGUI() {
key = new CheckBox();
key.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
//Something happens here
}
});
The parents classes gets instantiated before the children. In your top parent class you call the initGUI() abstract method, which its implementation is located in its child that doesn't not yet have its other fields initialized. It makes sense to move the actual initialization of the field to the initGUI() method, it fits the name convention and the logic of what you got.
Assignments in the declaration of instance variables, and any statements in non-static blocks within the class block, are run after the super() call has returned. If you call a method of the subclass from the superclass's constructor, it will be using the uninitialized this.
This is why there is a general rule that you should never call a virtual method from a constructor.

Categories