以圆类 Circle 为基础设计球类 Sphere

学习内容:实验二以圆类 Circle 为基础设计球类 Sphere

代码示例:

import java.util.Scanner;

class Point{
private double x;
private double y;
public Point(double x,double y) {
this.x=x;
this.y=y;
System.out.println("Point Constructor run");
}
public void setX(double x) {
this.x=x;
}
public double getX(){
return x;
}
public void setY(double y) {
this.y=y;
}
public double getY(){
return y;
}
public void show() {
System.out.println("("+x+","+y+")");
}
public double area() {
return 0;
}
}
class Circle extends Point {

private double x;
private double y;
private double radius;
static final double PI=3.14159;
public Circle(double x, double y,double radius) {
super(x, y);
this.radius=radius;
this.x=x;
this.y=y;
System.out.println("Circle Constructorrun");
}
public void setRadius(double radius) {
this.radius=radius;
}
public double getRadius(){
return radius;
}
public double circumference() {//计算圆的周长
return 2*PI*radius;
}
public double area() {//计算圆的面积
return PI*radius*radius;
}
public void show() {
System.out.println("("+x+","+y+"),Radius="+radius);
}
}
public class sphere1 extends Circle {

private double x;
private double y;
private double radius;
static final double PI=3.14159;
public sphere1(double x, double y, double radius) {
super(x, y, radius);
this.radius=radius;
this.x=x;
this.y=y;
System.out.println("Sphere Constructor run");
}
public double volume() {//计算球的体积
return (4.0/3.0)*PI*radius*radius*radius;
}
public double Area() {//计算球的表面积
return 4*PI*radius*radius;
}
public static void main(String[] args) {
double r;
System.out.println("请输入r:");
Scanner sc=new Scanner(System.in);
r=sc.nextDouble();
sphere1 s1=new sphere1(1,2,4);
sphere1 s2=s1;
s1.show();
System.out.println();//换行
System.out.println("Area="+s1.Area());//输出球的表面积
System.out.println("Volume="+s1.volume());//输出球的体积
s2.setRadius(r);//设置圆的半径
s2.show();
System.out.println("Area="+s2.area());//调用圆的面积函数
System.out.println("Circumference="+s2.circumference());//调用圆的周长函数
}

}

运行截图

 

 遇到的问题:

明天任务:Java类

posted @ 2020-07-29 09:44  CherriesOvO  阅读(486)  评论(0编辑  收藏  举报