java接口的使用方法
接口(interface)
接口无法被实例化,但是可以被实现。一个实现接口的类,必须实现接口内所描述的所有方法,否则就必须声明为抽象类。
据说适用于先由项目经理写接口,然后下发给底层程序员,一个个实现具体的方法和内容 (苦逼)
例如:
创建一个 Shape接口,声明两方法体
public interface Shape {
public double perimeter(double length,double width);//求周长
public double area(double length,double width);//求面积
}
然后创建一个Square 类,继承Shape
public class Square implements Shape {
@Override
public double perimeter(double length, double width) {
return length+width;
}
@Override
public double area(double length, double width) {
return length*width;
}
}
最后编译执行
public class Test {
public static void main(String[] args) {
Shape shape = new Square();
System.out.print(shape.perimeter(20,10));
}
}
30.0
Process finished with exit code 0
浙公网安备 33010602011771号