设计一个名为figure的图形软件包(package)。包中包含三角形、矩形、圆三个类。要求:(1)每个类都要构造方法并为成员设置get和set方法;(2)每个类都要有计算周长和面积的成员方法;(3)完成该软件包后的编码后,在另一个包的含有main方法的类中编写代码,分别使用图形软件包中的三个类,生成三个对象,并打印出其周长和面积。
这是方法一:
这是最开始写的,没啥问题,但是这个题说了每个类都要有计算周长和面积的成员方法,其实是在考察抽象类的使用,有空的话我会改改代码。。。
package figure;
public class CirCle {
public double r;
public CirCle() {
this.r = 0;
}
public CirCle(double r) {
this.r = r;
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
public double perimeter()//求周长函数
{
return Math.PI * 2 * r;
}
public double area()
{
return Math.PI * r * r;
}
}
package figure;
public class JuXing {
public double chang,kuan;
public JuXing() {
this.chang = 0;
this.kuan = 0;
}
public JuXing(double chang, double kuan) {
this.chang = chang;
this.kuan = kuan;
}
public double getChang() {
return chang;
}
public void setChang(double chang) {
this.chang = chang;
}
public double getKuan() {
return kuan;
}
public void setKuan(double kuan) {
this.kuan = kuan;
}
public double perimeter()//求周长函数
{
return 2*(chang + kuan);
}
public double area()
{
return chang*kuan;
}
}
package figure;
public class TriAngle {
public double a,b,c;//表示三角形的三条边
public TriAngle() {
this.a = 0;
this.b = 0;
this.c = 0;
}
public TriAngle(double a , double b , double c ) {
this.a = a;
this.b = b;
this.c = c;
}
public double getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public double getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
public double getC() {
return c;
}
public void setC(int c) {
this.c = c;
}
public double perimeter()//求周长函数
{
return a + b + c;
}
public double area()
{
double p = (a + b + c)/2;
return Math.sqrt(p*(p-a)*(p-b)*(p-c));//海伦公式
}
}
package figure_show;
import figure.CirCle;
import figure.JuXing;
import figure.TriAngle;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
TriAngle t = new TriAngle(3,4,5);
System.out.println("三角形的周长为:"+t.perimeter());
System.out.println("三角形的面积为:"+t.area());
JuXing p = new JuXing(3,4);
System.out.println("矩形的周长为:"+p.perimeter());
System.out.println("矩形的面积为:"+p.area());
CirCle c = new CirCle(5);
System.out.println("圆的周长为:"+c.perimeter());
System.out.println("圆的面积为:"+c.area());
}
}