【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());
	    }
	}
相关推荐
virus59455 小时前
悟空CRM mybatis-3.5.3-mapper.dtd错误解决方案
java·开发语言·mybatis
初次见面我叫泰隆6 小时前
Qt——3、常用控件
开发语言·qt·客户端
没差c6 小时前
springboot集成flyway
java·spring boot·后端
无小道7 小时前
Qt——QWidget
开发语言·qt
时艰.7 小时前
Java 并发编程之 CAS 与 Atomic 原子操作类
java·开发语言
梵刹古音7 小时前
【C语言】 函数基础与定义
c语言·开发语言·算法
编程彩机7 小时前
互联网大厂Java面试:从Java SE到大数据场景的技术深度解析
java·大数据·spring boot·面试·spark·java se·互联网大厂
笨蛋不要掉眼泪7 小时前
Spring Boot集成LangChain4j:与大模型对话的极速入门
java·人工智能·后端·spring·langchain
梵刹古音7 小时前
【C语言】 结构化编程与选择结构
c语言·开发语言·嵌入式
Yvonne爱编码7 小时前
JAVA数据结构 DAY3-List接口
java·开发语言·windows·python