已知在实验三(2)中用于描述 “三角形” 、“梯形”和“圆形”的Trangle、Lader和Circle类都具有周长和面积,尝试定义一个抽象父类Shape,并更改已实现的Trangle、Lader和Circle类,使得以下代码调用能够正常执行。
class ShapeTest{
public static void main(String[ ] args){
Shape shape;
shape = new Trangle(3,4,5);
shape.area();
shape.length();
shape = new Lader(4,2,3);
shape.area();
shape.length();
shape = new Circle(3.0);
shape.area();
shape.length();
}
}
package test_4;
public class Circle implements Shape{
double radius;
Circle() {
};
Circle(double radius) {
this.radius = radius;
};
public double getPerimeter() {
return 2*Math.PI*radius;
}
public double getArea() {
return radius*radius*Math.PI;
}
public void area() {
System.out.println(getArea());
};
public void length() {
System.out.println(getPerimeter());
};
}
package test_4;
public class Trangle implements Shape{
public int side1;
public int side2;
public int side3;
public Trangle() {
};
public Trangle(int side1,int side2,int side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
};
public double getArea() {
return side1*side2/2;
};
public double getPerimeter() {
return side1+side2+side3;
};
public void area() {
System.out.println(getArea());
};
public void length() {
System.out.println(getPerimeter());
};
}
package test_4;
public interface Shape {
public void area();
public void length();
}
package test_4;
public class ShapeTest {
public static void main(String[] args) {
Shape shape;
shape = new Trangle(3,4,5);
shape.area();
shape.length();
shape = new Circle(3.0);
shape.area();
shape.length();
}
}
接口和继承的关系:
相同点:都不可以被实例化,不能new操作;
不同点:抽象类可以有部分方法实现,接口所有方法不能实现
一个类只能继承(extends)一个类,实现(implements)多个接口
接口可以继承多个接口
抽象类有构造函数,接口没有