繁体   English   中英

如何在main中调用接口方法?

[英]How would I call an interface method in main?

我有一个在类上实现的抽象方法,但是当我尝试从main调用此方法时,它未显示在我的方法列表中。 显示所有其他方法,除了一种来自界面的方法。 我做错了什么?

public interface Printable {
    public void print();
} 

实现可打印。

@Override
    public void print() {
        for(int i = 0; i < getLength(); i++){
            for(int j = 0; j < getLength(); j++){
                System.out.println("o");
            }
            System.out.println();
        }   
    }

调用主可打印方法不可用。

if(shapes[i] instanceof Printable) {
    shapes[i]
}

尽管您在此处检查了形状是否可打印:

if(shapes[i] instanceof Printable){

编译器不知道您所做的。 它仍然认为shapesShape的数组,没有实现Printable 您必须告诉编译器“我确实检查过shape[i] 是否可打印,所以打印它!”

那怎么说呢?

投!

if(shapes[i] instanceof Printable){
    ((Printable)shape[i]).print();
}

您可能以前使用过此(type)value语法。 它将value强制转换为type 您可能已使用它将float值转换为int 这是同一件事!

实现可打印的类必须声明“ implements Printable”,仅拥有正确的方法还不够

还有这个:

if(shapes[i] instanceof Printable){
     shapes[i]
}

不调用打印

如果您的基本数组类型属于未实现Printable的类,则可以将其更改为使用Philipp编写的内容

class Base {}

class Shape extends Base implements Printable {
    void print()...
}

Base[] shapes = ....;

if(shapes[i] instanceof Printable) {
    Printable.class.cast(shapes[i]).print()   
}

要么

class Shape implements Printable {
    void print()...
}

Shape[] shapes = ....;

Shapes[i].print(); // no instanceof or cast necessary

暂无
暂无

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

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