面向对象具体例题

本代码模拟一个简单的绘图工具的原理(说明,画不出图来),绘制不同的形状以及不同颜色的图形。部分接口、类及其关系如图所示

 

 

 

package com.School.priv.Test;
    interface DrawCircle{  //绘制图形
        public void drawCircle (int radius,int x,int y);
}
    class RedCircle implements DrawCircle{  //绘制绿色圆形
        public void drawCircle (int radius,int x,int y ){
            System.out.println("Drawing Circle[red,radius:"+radius+
                    ",x:"+x+",y:"+y+"] ");
        }
    }
    class GreenCircle implements DrawCircle{
        public void drawCircle(int radius,int x,int y){
            System.out.println("Drawing Circle[green,radius:"+radius+
                    ",x:"+x+",y:"+y+"] ");
        }
    }
    
    abstract class Shape{   //形状
        Shape(){}
        protected DrawCircle drawCircle;
        public Shape (DrawCircle drawCircle){
        this.drawCircle=drawCircle;
    }
        public abstract void draw();
    }
    
     class Circle extends Shape{  //圆形
        private int x,y,radius;
        public Circle(int x,int y,int radius,DrawCircle drawCircle){
            super.drawCircle=drawCircle;
            this.x=x;
            this.y=y;
            this.radius=radius;
        }
        public void draw(){
            drawCircle.drawCircle (radius,x,y);
        }
    }
    
public class DrawCircleMain {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Shape  redCircle=new Circle(100, 100, 10, new RedCircle());
        Shape  greenCircle=new Circle(200, 200, 10, new GreenCircle());
        redCircle.draw();
        greenCircle.draw();
    }
}
运行结果:

Drawing Circle[red,radius:10,x:100,y:100] 
Drawing Circle[green,radius:10,x:200,y:200] 

————————————————————————————————————————————————————————写代码时遇到一个问题,Implicit super constructor Shape() is undefined. Must explicitly invoke another constructor

大概意思是  (机器翻译:隐式超级构造函数形状( )未定义。必须显式调用另一个构造函数)

在构造子类时,一定会调用到父类的构造方法。因为父类中的元素也需要被初始化。 
所以父类要么有一个默认的无参数构造,这样Java会自动调用这个无参数的构造。如果父类没有无参数的构造,那么就要你自己在子类的构造中,通过super()的方式调用父类的构造。 

所以我在父类中写了个无参构造的    Shape(){},解决了问题

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值