Java接口的声明和实现

Java接口的声明和实现

接口的声明和实现

接口的概念Interface接口的声明接口的实现接口的程序设计举例

接口的概念Interface

1.接口:用于声明一组类的公共操作的接口,Java中把对接口功能的继承称为实现(implement),接口只是声明了功能是什么,而并没有定义如何实现该功能,功能的实现是在继承这个接口的各个子类中完成的 2.组成:接口往往由一组常量和抽象方法组成,一般不包括变量和有具体实现的方法 3.性质:支持多重继承 【注】接口与抽象类的区别: (1)接口不能实现任何方法,而抽象类可以 (2)类可以实现许多接口,但只有继承一个父类 (3)接口不是类分级结构的一部分,没有联系的类可以实现相同的接口

接口的声明

定义接口的一般格式:

[ public ] interface 接口名 [ extends 父接口名列表 ]

{

[ public ] [ final ] [ static ] 类型 变量名 = 常量值 ; //常量声明

...

[ public ] [ abstract ] 返回类型 方法名 (参数列表) ; //抽象方法声明

...

}

例如Shape的接口声明:

public interface Shape

{

public final static double PI = 3.1416;

public abstract void draw(Graphics g);

}

接口的实现

实现接口一般格式:

class ClassName extends ParentClass implements interface1,interface2

{

... //接口中方法的实现

}

接口的程序设计举例

Write a program to complete following tasks (1)declare a interface name:Shape public interface Shape { public double getArea(); //return the surface area of shape public double getVolumn(); public double getName(); //return class name } (2)Define three classes Rectangle,Circle and Clinder to implements the following diagram (3)Define a class named ShapeTest to test above classes 【输出结果】 Rectangle: area=6.00, Volumn=0.00 Circle: area=50.27, Volumn=0.00 Clinder: area=251.33, Volumn=235.62

此处给出主函数

public class ShapeTest

{

public static void main(String[] args)

{

Shape s[] = new Shape[3];

s[0] = new Rectangle(2,3);

s[1] = new Circle(4);

s[2] = new Clinder(5,3);

for(Shape ele:s)

System.out.printf("%s: area=%.2f,Volumn=%.2f\n",ele.getName(),ele.getArea(),ele.getVolumn());

}

}

以下给出完整代码

package ml; //该java程序在ml包里

interface Shape //接口的定义

{

public double getArea();

public double getVolumn();

public String getName();

}

class Rectangle implements Shape

{

private int w;

private int l;

public Rectangle(int wValue,int lValue)

{

w = wValue;

l = lValue;

}

public double getArea()

{

return w*l;

}

public double getVolumn()

{

return 0;

}

public String getName()

{

return "Rectangle";

}

}

class Circle implements Shape

{

private int r;

public Circle(int rValue)

{

r = rValue;

}

public double getArea()

{

return Math.PI*r*r;

}

public double getVolumn()

{

return 0;

}

public double getLength()

{

return 2*Math.PI*r;

}

public String getName()

{

return "Circle";

}

}

class Clinder extends Circle

{

private int h;

public Clinder(int r,int height)

{

super(r);

h = height;

}

public double getArea()

{

return 2*super.getArea()+super.getLength()*h;

}

public double getVolumn()

{

return super.getArea()*h;

}

}

public class ShapeTest

{

public static void main(String[] args)

{

Shape s[] = new Shape[3];

s[0] = new Rectangle(2,3);

s[1] = new Circle(4);

s[2] = new Clinder(5,3);

for(Shape ele:s)

System.out.printf("%s: area=%.2f,Volumn=%.2f\n",ele.getName(),ele.getArea(),ele.getVolumn());

}

}

运行的结果为:

相关推荐

粳米是什么米?原来跟大米的区别是这样,注意这类人不宜吃粳米!
卡西欧TR500网友点评
365bet在线网址

卡西欧TR500网友点评

09-01 671
三哥发财不忘弟,弟弟当官却忘哥指代表什么生肖,精选落实解释