简体   繁体   English

在实现相同接口的类之间切换

[英]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)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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