黑马程序员技术交流社区

标题: 让技术飞,每日一题之面向对象编程。 [打印本页]

作者: 钟林杰    时间: 2013-4-14 08:46
标题: 让技术飞,每日一题之面向对象编程。
/*
每日一题之面向对象编程
今天这道题目有点难哦,主要考察的是面向对象编程的多态性,大家一起来试试吧,看看你是否能写出不一样的代码!
题目:父类Shape定义如下,要求用Square(正方形)和Circle(圆形)继承Shape并实现其抽象方法(只需打印出面积和中心坐标x,y即可),
                        并需要用动态联编技术实现。
abstract class Shape
{
        int x , y;
        Shape(int x , int y){this.x = x; this.y = y;}
        abstract void Draw();                                                                                                                                               
}
       

我程序的运行结果如下:
正方形的面积 = 400
中心坐标是:(10,10)
圆的面积 = 1256.0
中心坐标是:(10,10)       
(要看我的答案请先提交你的代码哦!)
*/

[hide=d10]
abstract class Shape                                                                                                                                                //定义抽象形状类
{
        int x , y;
        Shape(int x , int y){this.x = x; this.y = y;}
        abstract void Draw();                                                                                                                                               
}
class Square extends Shape                                                                                                                        //正方形类继承形状类
{
        int len ;
        Square(int x , int y ,int len){super(x,y);        this.len = len; }                                                                       
        void Draw(){System.out.println("正方形的面积 = " + (len*len) + "\n" + "中心坐标是:" + "("+ x +","+ y +")");}
}
class Circle extends Shape                                                                                                                        //圆形继承形状类
{
        int r;
        Circle(int x , int y ,int radius){super(x,y); this.r = radius;}
        void Draw(){System.out.println("圆的面积 = "+(r*r*3.14)+"\n" + "中心坐标是:" + "("+ x +","+ y +")");}
}
class DynamicBinding
{
        public static void main(String args[])
        {
                ShapeDraw(new Square(10,10,20));                                                                                        //将Square的匿名类初始化传给基类
                ShapeDraw(new Circle(10,10,20));                                                                                        //将Circle的匿名类初始化传给基类
        }
        public static void ShapeDraw(Shape s)
        {
                s.Draw();                                                                                                                                                                                        //通过给定的参数实现动态联编
        }
}[/hide]

作者: HM何伟    时间: 2013-4-14 10:06
来看看,你的想法是咋样的
作者: 钟林杰    时间: 2013-4-15 14:46
{:soso_e123:}居然没有一个人回答!!
作者: 李尧    时间: 2013-4-15 17:04
本帖最后由 李尧 于 2013-4-15 17:07 编辑

卤煮,这我不会.我决定这次直接看你的代码.
好吧..被你那个动态联编技术给吓到了....{:soso_e103:}




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2