接口可以用作数据类型,就像 String、int 等

Can interfaces be used as datatypes just like String,int etc

我正在搜索 AdapterView.java class。然后我 运行 到这个 problem.I 上传了 java 文件到下面 link

https://www.codepile.net/pile/7J7xq0LY

这里OnItemClickListener是一个接口(写在第278行)。在第 146 行,它给出为 OnItemClickListener mOnItemClickListener;。怎么可能 .mOnItemClickListener 是一个成员变量。把它放在接口名称旁边对我来说没有意义。当我们声明一个变量时,我们首先写变量类型,然后是名称。但在这里它并没有形成逻辑。谁能给我解释一下。我刚刚了解了接口,因此对其基础知识不太自信。提前致谢

Can interfaces be used as datatypes just like String,int etc.

是的,interface 也是一种类似于 class 的类型。在Java中使用了一个interface引用来实现多态。

查看 this 了解更多信息。

下面给出了演示此概念的示例代码:

interface Polygon {
    double getArea();
}

class Triangle implements Polygon {
    private double base, height;

    public Triangle(double base, double height) {
        this.base = base;
        this.height = height;
    }

    public double getBase() {
        return base;
    }

    public void setBase(double base) {
        this.base = base;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    @Override
    public double getArea() {
        return 0.5 * base * height;
    }

}

class Rectangle implements Polygon {

    private double length, breadth;

    public Rectangle(double length, double breadth) {
        this.length = length;
        this.breadth = breadth;
    }

    public double getLength() {
        return length;
    }

    public void setLength(double length) {
        this.length = length;
    }

    public double getBreadth() {
        return breadth;
    }

    public void setBreadth(double breadth) {
        this.breadth = breadth;
    }

    @Override
    public double getArea() {
        return length * breadth;
    }
}

public class Main {
    public static void main(String[] args) {
        Polygon shape1 = new Triangle(10, 20);
        Polygon shape2 = new Rectangle(10, 20);
        System.out.println(shape1.getArea());
        System.out.println(shape2.getArea());
    }
}

输出:

100.0
200.0

如有任何问题,请随时发表评论 doubt/issue。