java编程 抽象类 设计一个图形抽象类,然后让圆和矩形两个类继承它,这两个类都有一个计算面积的方法,
展开全部
这个是三角 圆和矩形的,你参考下,可以计算面积和周长
public class HHsa {
public static void main(String[] args) {
Geometric g=new Triangle(3,4,5);
System.out.println(g.getArea());
System.out.println(g.getPerimeter());
g=new Rectangle(2,3);
System.out.println(g.getArea());
System.out.println(g.getPerimeter());
g=new Circle(1);
System.out.println(g.getArea());
System.out.println(g.getPerimeter());
}
}
abstract class Geometric{
public abstract double getArea();
public abstract double getPerimeter();
}
class Triangle extends Geometric{
int a;
int b;
int c;
public Triangle(int a,int b,int c){
this.a=a;
this.b=b;
this.c=c;
}
public double getArea(){
double s=0.25*Math.sqrt((a+b+c)*(a+b-c)*(a-b+c)*(b+c-a));
return s;
}
public double getPerimeter(){
return a+b+c;
}
}
class Rectangle extends Geometric{
int a;
int b;
public Rectangle(int a,int b){
this.a=a;
this.b=b;
}
public double getArea(){
return a*b;
}
public double getPerimeter(){
return 2*(a+b);
}
}
class Circle extends Geometric{
int r;
public Circle(int r){
this.r=r;
}
public double getArea(){
return Math.PI*r*r;
}
public double getPerimeter(){
return 2*Math.PI*r;
}
}
public class HHsa {
public static void main(String[] args) {
Geometric g=new Triangle(3,4,5);
System.out.println(g.getArea());
System.out.println(g.getPerimeter());
g=new Rectangle(2,3);
System.out.println(g.getArea());
System.out.println(g.getPerimeter());
g=new Circle(1);
System.out.println(g.getArea());
System.out.println(g.getPerimeter());
}
}
abstract class Geometric{
public abstract double getArea();
public abstract double getPerimeter();
}
class Triangle extends Geometric{
int a;
int b;
int c;
public Triangle(int a,int b,int c){
this.a=a;
this.b=b;
this.c=c;
}
public double getArea(){
double s=0.25*Math.sqrt((a+b+c)*(a+b-c)*(a-b+c)*(b+c-a));
return s;
}
public double getPerimeter(){
return a+b+c;
}
}
class Rectangle extends Geometric{
int a;
int b;
public Rectangle(int a,int b){
this.a=a;
this.b=b;
}
public double getArea(){
return a*b;
}
public double getPerimeter(){
return 2*(a+b);
}
}
class Circle extends Geometric{
int r;
public Circle(int r){
this.r=r;
}
public double getArea(){
return Math.PI*r*r;
}
public double getPerimeter(){
return 2*Math.PI*r;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询