Sw3das
Sw3das

Reputation: 157

Override method from assigned class

I want to override method from class that's already assigned to a variable.
For example:

inventory = new Inventory( );

/* Some code here that changes how inventory
must behave or whatever */

inventory
{
    @Override ...
}

Is it possible ???

Upvotes: 0

Views: 39

Answers (2)

Vince
Vince

Reputation: 15146

Composition would definitely help here. Rather than overriding a method to change the behavior of Inventory, pass it the method:

class Inventory {
    private MyMethod method;

    public void setMethod(MyMethod method) {
        this.method = method;
    }

    public void doSomething() {
        method.doSomething();
    }
}

interface MyMethod {
    void doSomething();
}

You can now switch the implementation of MyMethod via setMethod:

Inventory inv = new Inventory();
//...

inv.setMethod(() -> {
    //write method here
});

If you aren't using Java 8, you'll have to subclass MyMethod:

inv.setMethod(new MyMethod() {
    public void doSomething() {

    }
});

Upvotes: 1

yasd
yasd

Reputation: 956

Maybe you think of something like this (instead of the null-if you could implement a default strategy to make it more clean):

public interface Strategy {

    public void doSomething();

}

public class Inventory {

    Strategy strategy;

    public Inventory() {
        // ...
    }

    public void doSomething() {
        if (strategy == null) {
            System.out.println("strategy is empty");
        } else {
            strategy.doSomething();
        }
    }

    public Strategy getStrategy() {
        return strategy;
    }

    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }

}

Then this

    Inventory inventory = new Inventory();
    inventory.doSomething();
    inventory.setStrategy(new Strategy() {

        @Override
        public void doSomething() {
            System.out.println("strategy is now something different");
        }

    });
    inventory.doSomething();

shows this:

strategy is empty
strategy is now something different

For a more elaborated version you can take a look at the strategy pattern.

Upvotes: 1

Related Questions