通过两个类计算一个长方形的周长和面积

1 问题

如果要计算长方形的面积和周长,我们一般都会将所需要的编程代码放在一个类里面,但这样其实并不方便我们操作,代码太多的话,在一个类里常常让我们头脑不清晰,而且如果报错的话,我们会花很长时间来找错误,会浪费很多时间,所以怎样使编码逻辑更清晰明了呢?

2 方法

代码清单 1

|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| package Prictice; //创建第一个类 public class MyBox { private double length; private double width; public MyBox(){ super(); } //设置长和宽 public MyBox(double length, double width){ this.length = length; this.width = width; } public double getLength(){ return length; } public void setLength(double length){ this.length = length; } public double getWidth(){ return width; } public void setWidth(double width){ this.width = width; } //求面积和周长 public double area(){ return this.length * this.width; } public double circ(){ return (this.length + this.width)*2; } } package Prictice; //创建第二个类 //Test01是MyBox的子类,MyBox是Test01的父类 public class Test01 extends MyBox { public static void main(String\[\] args) { MyBox b = new MyBox(); b.setLength(2); System.out.println("长:"+b.getLength()); b.setWidth(3); System.out.println("宽:"+b.getWidth()); double area = b.area(); System.out.println("面积:"+area); double circ = b.circ(); System.out.println("周长:"+circ); } } |

3 结语

针对怎样使得求长方形的面积和周长这个编码逻辑更加清晰明了的问题,提出上述方式,通过建立两个类来实现,一个类主要是创建对象,对对象的数据类型进行设置,一个主要就是代入数据,保证程序的正常进行。通过亲自实验,证明该方法是可行且有效的,本文的方法只是其中一种,可能还有更多的方法来解决这个问题,同时,在编程上仍有考虑不周的地方,还有值得完善的地方,未来可以继续研究更加简洁方便的代码进行处理。

相关推荐
小白学大数据24 分钟前
Codex 里的 GPT 6 Astra、GPT 5.6 Sol、Terra、Luna 怎么选
开发语言·gpt·microsoft
l1t2 小时前
DeepSeek 4.1总结的Tom Lane 谈塑造 Postgres 三十年历程的架构决策
开发语言·数据库·postgresql·架构
变与不变8062 小时前
Debug 调试与排错规范
前端·javascript
欢迎来到祖安!2 小时前
企业微信 API 接口能力介绍:支持消息收发、图片发送、表情互动、联系人管理等多场景应用
java·前端·数据仓库·spring cloud·企业微信
dadaobusi6 小时前
学习:RV lkvm SBI
java·学习·spring
djarmy8 小时前
MAIN.c(1): warning C318: can’t open file ‘STC8G.H’ 报错 解决 分析
c语言·开发语言·mongodb
HEJOO98 小时前
深入理解 Java volatile 关键字:原理、用法与常见误区
java·开发语言·spring
曹牧8 小时前
Java:no content to map due to end of input
java·开发语言
阿维的博客日记8 小时前
Example 类全场景实战指南
java·mybatis
梦梦代码精8 小时前
《回收租赁系统技术选型避坑指南:业务闭环与二开自由度详解》
开发语言·低代码·docker·开源·代码规范