【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());
	    }
	}
相关推荐
骄马之死5 小时前
SpringMVC + SpringBoot 核心知识点总结
java·spring boot·后端
z落落5 小时前
C# 泛型方法(原理、类型推断、多泛型参数)+泛型效率(普通类型 VS Object装箱 VS 泛型)
开发语言·c#
L_09075 小时前
【C++】异常
开发语言·c++
世辰辰辰6 小时前
批量修改图片/文本名子
开发语言·python·批量修改文件名
郑洁文6 小时前
基于Spring Boot的流浪动物救助网站
java·spring boot·后端·毕设·流浪动物救助
螺丝钉code7 小时前
JAVA项目 Claude code CLAUDE.md 到底应该怎么写
java·人工智能·claude code
z落落8 小时前
C# 四种特殊类:抽象类、密封类、静态类、部分类
开发语言·c#
摇滚侠8 小时前
Maven 入门+高深 单一架构案例 54-59
java·架构·maven·intellij-idea
VidDown9 小时前
Webhook 调试器:让第三方回调“原形毕露”
java·开发语言·javascript·编辑器·postman
折哥的程序人生 · 物流技术专研9 小时前
Java 23 种设计模式:从踩坑到精通 | 原型模式 —— 克隆对象,深拷贝与浅拷贝的坑你踩过吗?
java·设计模式·架构·原型模式·单一职责原则