📄 deo.java
字号:
//利用多态性编程,创建一个square类,实现求三角形、正方形和圆形面积。方法
//抽象出一个共享的类,定义一个函数求面积的公共界面。再重新定义各面积的求面积
//函数,在主类中创建不同类的对象,并求不同形状的面积
//学生:刘建强 03312008
abstract class Shape
{int position_x,position_y; //坐标变量
double PI=3.14159;
//void MoveTo(int new_pos_x,int new_pos_y);
//{position_x=new_pos_x;
//position_y=new_pos_y;
//}
abstract void draw();//抽象方法
abstract double area();//抽象方法
}
class Square extends Shape
{int length;
void setSize(int l)
{length=l;}
void draw()
{System.out.println("this is a square.");
//以(position_x,position_y)为中心,画出一个边长是length的正方形
}
public double area()
{return length*length;//求正方形面积
}
}
class Circle extends Shape
{int radius;
void setSize(int r)
{radius=r;//给定半径
}
void draw()
{System.out.println("this is a circle.");
//以(position_x,position_y)为中心,画出一个半径是radius的圆
}
public double area()
{return PI*radius*radius;//求圆的面积
}
}
class Trigon extends Shape
{ int bottom;
int highness;
void setsize(int b,int h)
{bottom=b;highness=h;}
void draw()
{System.out.println("this is a trigon.");
//以(position_x,position_y)为中心,
//画出一个底为bottom,高为highness的三角形
}
public double area()
{return 0.5*bottom*highness;}
}
class ShapeManager
{void manager(Shape obj)
{obj.draw();}
}
public class deo
{public static void main(String args[])
{ShapeManager shape_man=new ShapeManager();
Square sq=new Square();
Circle ci=new Circle();
Trigon tr=new Trigon();
shape_man.manager(sq);
sq.setSize(5);
System.out.println("Area of the square is"+sq.area());
shape_man.manager(ci);
ci.setSize(2);
System.out.println("Area of the circle is"+ci.area());
shape_man.manager(tr);
tr.setsize(5,7);
System.out.println("Area of the trigon is"+tr.area());
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -