John Doe
John Doe

Reputation: 13

Switch between classes which implement a same interface

Let's say I have this code.

public interface A {
    public boolean move();
}

public class B implements A {
    public boolean move() {
        // do some stuff
        // return true
    }
}

public class C implements A {
    public boolean move() {
        // don't do anything
        // return false
    }
}

Can I do something like this?

B cell = new B();
// move() method will return True and will do some stuff
// now I'd like to change the B cell to C cell
// move() method will return False and won't do anything

Thanks for any help!

I hope the code should be enough.

Upvotes: 1

Views: 213

Answers (1)

ControlAltDel
ControlAltDel

Reputation: 35096

The trick is to use the interface (A) instead

A cell = new B();
//or
//A cell = new C();

Upvotes: 1

Related Questions