定义一个抽象类Shape,成员有图形名称(name)和求面积的抽象方法Area(),利用继承产生子类三角形类Trangle类,圆Circle类,矩形Rectangle类。并分别实现计算面积的方法计算相应图形的面积。对于Trangle类要求能够实现修改三边,判断三边是否能够构成三角形,根据三边长计算面积的方法。
- abstract class shape
- {
- String name;
- abstract void Area();
- }
- class Trangle extends shape //三角形类
- { Trangle(){}
- double sideA,sideB,sideC;
- boolean boo;
- public Trangle(double a,double b,double c)
- {
- sideA=a;sideB=b;sideC=c;
- this.name="三角形";
- if(a+b>c&&a+c>b&&b+c>a)
- {
- System.out.println("我是一个三角形");
- boo=true;
- }
- else
- {
- System.out.println("我不是一个三角形");
- boo=false;
- }
- }
- public void Area()
- {
- if(boo)
- {
- double p=(sideA+sideB+sideC)/2.0;
- double area=Math.sqrt(p*(p-sideA)*(p-sideB)*(p-sideC));
- System.out.println(name+"面积是:"+area);
- }
- else
- {
- System.out.println("不是一个三角形,不能计算面积");
- }
- }
- public void 修改三边(double a,double b,double c)
- {
- sideA=a;sideB=b;sideC=c;
- if(a+b>c&&a+c>b&&b+c>a)
- {
- boo=true;
- }
- else
- {
- boo=false;
- }
- }
- }
- class Circle extends shape //圆类
- {
- double r;
- Circle(double r)
- {
- this.r=r;this.name="圆";
- }
- public void Area()
- {
- System.out.println(name+"面积是:"+3.14*r*r);
- }
- }
- class Rectangle extends shape //矩形类
- {
- double a,b;
- Rectangle(double a,double b)
- {
- this.a=a;this.b=b;this.name="矩形";
- }
- public void Area()
- {
- System.out.println(name+"面积是:"+a*b);
- }
- }
- class 图形1
- {
- public static void main(String[] args)
- {
- Trangle t=new Trangle(1,2,3);
- t.Area();
- t.修改三边(3,4,5);
- t.Area();
- Circle c=new Circle(2);
- c.Area();
- Rectangle r=new Rectangle(4,5);
- r.Area();
- }
- }
对于上题目中的Shape类,改用接口来实现同样的功能
- interface shape
- {
- final String name="图形";
- void Area();
- }
- class Trangle implements shape
- {
- Trangle(){}
- double sideA,sideB,sideC;
- boolean boo;
- public Trangle(double a,double b,double c)
- {
- sideA=a;sideB=b;sideC=c;
- if(a+b>c&&a+c>b&&b+c>a)
- {
- System.out.println("我是一个三角形");
- boo=true;
- }
- else
- {
- System.out.println("我不是一个三角形");
- boo=false;
- }
- }
- public void Area()
- {
- if(boo)
- {
- double p=(sideA+sideB+sideC)/2.0;
- double area=Math.sqrt(p*(p-sideA)*(p-sideB)*(p-sideC));
- System.out.println(name+"面积:"+area);
- }
- else
- {
- System.out.println("不是一个三角形,不能计算面积");
- }
- }
- public void 修改三边(double a,double b,double c)
- {
- sideA=a;sideB=b;sideC=c;
- if(a+b>c&&a+c>b&&b+c>a)
- {
- boo=true;
- }
- else
- {
- boo=false;
- }
- }
- }
- class Circle implements shape //圆类
- {
- double r;
- Circle(double r)
- {
- this.r=r;
- }
- public void Area()
- {
- System.out.println(name+"面积是:"+3.14*r*r);
- }
- }
- class Rectangle implements shape //矩形类
- {
- double a,b;
- Rectangle(double a,double b)
- {
- this.a=a;this.b=b;
- }
- public void Area()
- {
- System.out.println(name+"面积是:"+a*b);
- }
- }
- class A
- {
- public void t(shape s) //接口类型参数
- {
- s.Area(); //接口回调
- }
- }
- class 图形2
- {
- public static void main(String[] args)
- {
- shape s;
- s=new Trangle(3,4,5);
- s.Area() ; //接口回调
- A a=new A();
- a.t(new Circle(2));
- a.t(new Rectangle(3,4));
- }
- }