写一个Shape抽象类:
具有属性:周长和面积;
具有求周长的抽象方法
定义其子类三角形和矩形:
分别具有求周长的方法。
定义主类E,
在其main方法中创建三角形和矩形类的对象
并赋给Shape类的对象a、b,使用对象a、b来测试其特性
abstract class Shape{
double zc;
double mj;
public abstract double jisuanzc( );
}
class sanjiao extends Shape{
double b1,b2,b3;
void fuzhi(double a,double b,double d){
b1=a;
b2=b;
b3=d;
}
public double jisuanzc() {
return (b1+b2+b3);
}
}
class juxing extends Shape{
double c,k;
void fuzhi(double e,double f){
c=e;
k=f;
}
public double jisuanzc() {
return (2*c+2*k);
}
}
public class E {
public static void main(String args[]){
sanjiao s=new sanjiao();
s.fuzhi(3,4,5);
juxing j=new juxing();
j.fuzhi(3,5);
System.out.println(s.jisuanzc());
System.out.println(j.jisuanzc());
}
}
编写一个Java应用程序,要求实现如下类之间的继承关系:
(1)编写一个抽象类Shape,该类具有两个属性:周长length和面积area,具有两个抽象的方法:计算周长getLength()和计算面积getArea()。
(2)编写非抽象类矩形Rectangle和圆形Circle继承类Shape。
(3)编写一个锥体类Cone,里面包含两个成员变量Shape类型的底面bottom和double类型的高height。
(4)定义一个公共的主类TestShape,包含一个静态的方法void compute(Shape e),通过该方法能够计算并输出一切图形的周长和面积;在主方法中调用compute方法,计算并输出某矩形和圆形的周长和面积,并测试锥体类Cone。
abstract class Shape {
double length, area;
abstract double getLength();
abstract double getArea();
}
class Rectangle extends Shape {
double a, b;
Rectangle(double a, double b) {
this.a = a;
this.b = b;
}
double getLength() {
return(2*a+2*b);
}
double getArea() {
return(a*b);
}
}
class Circle extends Shape {
double r,pi=3.14;
Circle(double r) {
this.r = r;
}
double getLength() {
return (2*pi*r);
}
double getArea(){
return (pi*r*r);
}
}
class Cone {
Shape bottom;
double height;
Cone(Shape bottom, double height) {
this.bottom = bottom;
this.height = height;
}
double getzhi(){
return bottom.getArea()*height/3;
}
}
public class TestShape {
public static void compute(Shape e){
System.out.println("面积为"+e.getArea());
System.out.println("周长为"+e.getLength());
}
public static void main(String[] args) {
System.out.println("该矩形");
Rectangle re=new Rectangle(2,4);
compute(re);
System.out.println("该圆形");
Circle ci=new Circle(5);
compute(ci);
System.out.println("该锥体");
Cone co=new Cone(ci,5);
System.out.println("体积为"+co.getzhi());
}
}