【Java每日一题】— —第二十四题:编程定义一个长方形类Rectangle(2023.10.08)

🕸️Hollow,各位小伙伴,今天我们要做的是第二十四题。

🎯问题:

**(**1)定义成员变量:长(int height),宽(int width);

(2)定义无参构造方法,带参构造方法;

(3)定义以上成员变量对应的getXxx()/setXxx()方法;以及一个显示所有成员信息的toString()方法;

(4)定义求周长的zhouChang()方法和求面积的area()方法;

(5)定义一个测试类RectangleDemo, 进行测试,分别用无参构造方法和带参构造方法创建对象,计算周长和面积。测试结果如下:

🎯 结果:

java 复制代码
public class Java2{
		private int height;
		private int width;
		public Java2() {//无参构造方法
		}
		public Java2(int heingt,int width) {//有参构造方法
			this.height=heingt;
			this.width=width;
		}
		public int getHeight() {
			return height;
		}
		public void setHeight(int height) {
			this.height = height;
		}
		public int getWidth() {
			return width;
		}
		public void setWidth(int width) {
			this.width = width;
		}
		@Override
		public String toString() {
			// TODO Auto-generated method stub
			return "Rectangle [ width="+width+",height="+height;
		}
		public int zhouChang() {
			return 2*(height+width);
		}
		public int area() {
			return height*width;
		}
		public static void main(String[] args) {
			 // 创建无参构造方法的对象
	        Java2 rectangle1 = new Java2();
	        rectangle1.setHeight(10);
	        rectangle1.setWidth(8);
	        System.out.println(rectangle1.toString());
	        System.out.println("周长为:" + rectangle1.zhouChang());
	        System.out.println("面积为:" + rectangle1.area());

	        // 创建带参构造方法的对象
	        Java2 rectangle2 = new Java2(12, 9);
	        System.out.println(rectangle2.toString());
	        System.out.println("周长为:" + rectangle2.zhouChang());
	        System.out.println("面积为:" + rectangle2.area());
	    }
	}
相关推荐
Cao12345678932119 分钟前
扫雷-C语言版
c语言·开发语言
天堂的恶魔94630 分钟前
QT —— 信号和槽(槽函数)
开发语言·qt
牛马baby34 分钟前
Springboot 自动装配原理是什么?SPI 原理又是什么?
java·spring boot·后端
水w36 分钟前
【Python爬虫】详细入门指南
开发语言·爬虫·python·scrapy·beautifulsoup
小小深1 小时前
了解JVM
java·jvm
Sunlight_7771 小时前
第五章 SQLite数据库:1、SQLite 基础语法及使用案例
java·linux·服务器·jvm·数据库·tcp/ip·sqlite
JhonKI1 小时前
【从零实现高并发内存池】内存池整体框架设计 及 thread cache实现
java·redis·缓存
何似在人间5751 小时前
SpringAI+DeepSeek大模型应用开发——4 对话机器人
java·机器人·大模型应用开发·spring ai
Susea&1 小时前
数据结构初阶:双向链表
c语言·开发语言·数据结构
pianmian12 小时前
arcgis几何与游标(1)
开发语言·python