简体   繁体   中英

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.

The trick is to use the interface (A) instead

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM