win8风格网站开发实例/万秀服务不错的seo推广
12.3每日一题
今天又是深化面向对象的一天~
题目简介:
建立一个Po(点)类,包含数据成员X,Y(坐标点),构造器;
以Po为父类,实现一个Circle(圆)类作为子类,增加数据成员R(半径),构造器、求圆面积方法getArea(),求圆周长方法getCircumference();
再以Cicle类为父类,实现出一个Cylinder (圆柱体〕子类,增加数据成员H(高),构造器,求圆柱体积方法getVolumn()、求圆柱表面积方法getArea(),请编写程序实现。(圆周率取3.14)
要求:
自定义各个类的toString方法,要求当上面三个类的对象创建完毕后,我们直接打印这个三个对象可以显示这个对象的完整信息。
如打印Circle类的对象会输出:
Circle{X=1,Y=2,R=1,circumference=6.28,area=3.14}
友情提示X,Y,R应均为double类型;
思考:
今天也是一道常规的面向对象类型题目,主要考察大家对于类继承的使用以及重写toString()方法。
代码:
/**@author xiangguang*/public class Test {public static void main(String[] args) {Po po = new Po(1.0, 2.0);Circle circle = new Circle(1.0, 2.0, 1.0);Cylinder cylinder = new Cylinder(1.0, 2.0, 1.0, 2.0);System.out.println(po);System.out.println(circle);System.out.println(cylinder);}}
class Po{//坐标属性private double X;private double Y;public Po(){}public Po(double x,double y){this.X=x;this.Y=y;}//重写toString方法@Overridepublic String toString() {return "Po{" +"X=" + X +",Y=" + Y +'}';}//提供私有属性get/set方法public double getX() {return X;}public void setX(double x) {this.X = x;}public double getY() {return Y;}public void setY(double y) {this.Y = y;}
}
class Circle extends Po{//增加半径属性private double R;public static final double PI = 3.14;//提供构造器public Circle(){}public Circle(double x,double y,double r){super(x,y);this.R=r;}//求面积方法public double getArea(){return R*R*PI;}//求周长方法public double getCircumference(){return R*PI*2;}//重写toString@Overridepublic String toString() {return "Circle{" +"X=" + this.getX() +",Y=" + this.getY() +",R=" + R +","+"Circumference="+this.getCircumference()+",Area="+this.getArea()+'}';}//提供get/set方法public double getR() {return R;}public void setR(double r) {this.R = r;}
}
class Cylinder extends Circle{//添加高度属性private double H;//提供构造器public Cylinder(){}public Cylinder(double x,double y,double r,double h){super(x, y, r);this.H=h;}//提供方法public double getVolume(){return super.getArea()*H;}@Overridepublic double getArea(){return super.getArea()*2+super.getCircumference()*H;}//重写toString@Overridepublic String toString() {return "Cylinder{" +"X=" + this.getX() +",Y=" + this.getY() +",R=" +this.getR() +",H=" + H +",volume="+this.getVolume()+",Area="+this.getArea()+'}';}
}