1、按要求编写一个Java应用程序
(1)定义一个接口Shape,有求周长和面积的方法。
(2)定义一个圆形类Circle,继承Shape。
(3)创建一个Shape[]数组,存储三个圆形。
(4)计算数组中所有圆形的总面积和总周长。
package Day0921.D01;
/**
定义接口类Shape
*/
public interface Shape {
// 求周长
double getPer();
// 求面积
double getArea();
}
package Day0921.D01;
public class Circle implements Shape {
private final double PI = 3.14;
private double r;
public double getPI() {
return PI;
}
public double getR() {
return r;
}
public void setR(int r) {
this.r = r;
}
public Circle() {
}
public Circle(int r) {
this.r = r;
}
@Override
public double getPer() {
return 2 * PI * r;
}
@Override
public double getArea() {
return PI * r * r;
}
}
package Day0921.D01;
public class Test {
public static void main(String[] args) {
Shape[] s = new Shape[3];
// 向上转型,最后是Shape类型
s[0] = new Circle(5);
s[1] = new Circle(10);
s[2] = new Circle(15);
// 取出的类型:Shape
double sumPer = 0;
double sumArea = 0;
for (Shape shape : s) {
sumArea += shape.getArea();
sumPer += shape.getPer();
}
System.out.println(sumArea);
System.out.println(sumPer);
}
}
2、定义一个台灯类Lamp,有一个灯泡属性,还有一个开灯的方法。灯泡分为红灯泡和绿灯泡,都有发光的方法。要求:在不修改台灯代码的前提下,更换灯泡发出不同的光。
package Day0921.D02;
public class Lamp {
private Bubble b;
public Bubble getB() {
return b;
}
public void setB(Bubble b) {
this.b = b;
}
public void open() {
b.light();
}
}
package Day0921.D02;
public class Bubble {
public void light(){
System.out.println("发光");
}
}
package Day0921.D02;
public class GreenBubble extends Bubble{
@Override
public void light() {
System.out.println("发绿光");
}
}
package Day0921.D02;
public class RedBubble extends Bubble{
@Override
public void light() {
System.out.println("发红光");
}
}
package Day0829.D02;
import java.awt.*;
public class Test {
public static void main(String[] args) {
RedBubble r = new RedBubble();
GreenBubble g = new GreenBubble();
Lamp l = new Lamp();
l.setB(r);
l.open();
l.setB(g);
l.open();
}
}