package jiekou1; public interface ShapePara { //定义常量PI final double PI=3.14; //定义抽象方法 //获得图形面积 double getArea(); //获得图形周长 double getCircumference(); }
package jiekou1; public class Circle implements ShapePara { //定义成员变量 public double radius; public double x; public double y; //定义构造方法 Circle(double radius) { this.radius=radius; this.x=0; this.y=0; } //定义成员方法 //返回半径的值 double getRadius() { return radius; } //写入圆心的坐标 void setCenter(double x, double y) { this.x=x; this.y=y; } //写入圆的半径 void setRadius(double radius) { this.radius=radius; } //完善得到面积和周长的方法 @Override public double getArea() { return PI*radius*radius; } @Override public double getCircumference() { return 2*PI*radius; } }
package jiekou1; public class Shape { //成员变量 private ShapePara sp; public ShapePara getSp() { return sp; } public void setSp(ShapePara sp) { this.sp = sp; } //定义成员方法获得图形面积 void getArea() { System.out.println(sp.getArea()); } //定义成员方法获得图形周长 void getCircumference() { System.out.println(sp.getCircumference()); } }
package jiekou1; public class Rect extends Shape { //定义成员变量 private double a; private double b; public double getA() { return a; } public void setA(double a) { this.a = a; } public double getB() { return b; } public void setB(double b) { this.b = b; } void getArea() { System.out.println("矩形的面积为:"+a*b); } }
package jiekou1; public class Text_mianji { public static void main(String[] args) { Shape yy= new Shape(); //匿名对象 Circle cl= new Circle(5); cl.setCenter(0, 1); cl.setRadius(12); yy.setSp(cl); System.out.println("圆的圆心坐标为:("+cl.x+","+cl.y+")"); System.out.println("半径为:"+cl.radius); System.out.print("圆的面积为:"); yy.getArea(); System.out.print("圆的周长为:"); yy.getCircumference(); //实例化矩形对象 Rect re = new Rect(); re.setA(20); re.setB(12.5); System.out.println("矩形的长为:"+re.getA()+" 矩形的宽为:"+re.getB()); re.getArea(); } }
时间: 2024-10-08 20:50:34