以圆类 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类包
__EOF__

本文链接:https://www.cnblogs.com/zyj3955/p/13395313.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!