- interface Share
- {
- public float getArea() throws AreaException;
- }
- class AreaException extends Exception
- {
- protected AreaException(String msg){
- super(msg);
- }
- }
- abstract class ShareAbstract
- {
- private static final double PI=3.1415;
- protected static double getPI(){
- return PI;
- }
- }
- class Rec extends ShareAbstract implements Share
- {
- private static int len;
- private Rec(int len){
- this.len=len;
- }
- private static Rec rec;
- public static Rec getIntance(){
- return rec=new Rec(len);
- }
- public void setLen(int len){
- this.len=len;
- }
- public float getArea() throws AreaException{
- if(len<0){
- throw new AreaException("圆的半径 r < 0");
- }
- return (float)(ShareAbstract.getPI()*len*len);
- }
- }
- class Square implements Share
- {
- private int len;
- protected Square(int len){
- this.setLen(len);
- }
- public void setLen(int len){
- this.len=len;
- }
- public int getLen(){
- return this.len;
- }
- public float getArea() throws AreaException{
- if(len<0){
- throw new AreaException("正方形的边长小于零");
- }
- return (float)(len*len);
- }
- }
- class ShareDemo
- {
- public static void doGet(Share share){
- try{
- System.out.println(share.getArea());
- }catch(AreaException e){
- System.out.println("e.getMessage()");
- }
- }
- public static void main(String[] args)
- {
- Rec.getIntance().setLen(4); //使用单例无法修改 Rec的属性 len, 求解决....
- doGet(Rec.getIntance());
- }
- }
复制代码 |