实验三
定义接口,声明若干个abstract方法;创建类,在类中定义若干个参数为接口类型的方法,通过实现接口的类的对象回调类重写的接口方法,实现相应功能,最后完成实验报告。
输出成功
package com.experimental;
interface IShape
{
static final double PI=3.14;
abstract double getArea(); //声明抽象方法
abstract double getLength(); //声明抽象方法
}
class Circle implements IShape //以IShape接口来实现Circle类
{
double radius;
public Circle(double r)
{
radius=r;
}
public double getArea() //实现接口中getArea()方法
{
return PI*radius*radius;
}
public double getLength() //实现接口中getLength()方法
{
return 2*PI*radius;
}
}
class Rectangle implements IShape //以IShape接口来实现Rectangle类
{
private double width;
private double height;
public Rectangle(double width,double height)
{
this.width=width;
this.height=height;
}
public double getArea() //实现接口中getArea()方法
{
return width*height;
}
public double getLength()//实现接口中getLength()方法
{
return 2*(width+height);
}
}
public class experimental { //主类
public static void main(String[] args) {
IShape circle=new Circle(4.0); //声明父接口变量circle,指向子类对象
System.out.print("圆面积="+circle.getArea()); //接口回调
System.out.println(";周长="+circle.getLength()); //接口回调
Rectangle rect=new Rectangle(6.5,10.8); //声明rectangle类的变量rect
System.out.print("矩形面积="+rect.getArea()); //接口回调
System.out.println(";周长="+rect.getLength()); //接口回调
}
}