综合案例讲解
案例
1、定义一个长方形类,定义求周长和面积的方法,然后定义一个测试类,进行测试。
public class anli { public static void main(String[] args) { Rectangle rectangle = new Rectangle(10,20); System.out.println("长方形周长:"+rectangle.getPermeter()); System.out.println("长方形面积:"+rectangle.getArea()); } } class Rectangle{ private int length; private int width; /** * 周长 */ public int getPermeter(){ return this.length*2+this.width*2; } /** * 面积 */ public int getArea(){ return this.length*this.width; } public Rectangle() { } public Rectangle(int length, int width) { this.length = length; this.width = width; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } }
运行结果:
2、封装一个学生类,有姓名,有年龄,有性别,有英语成绩,数学成绩,语文成绩,封装方法,求总分,平均分,以及打印学生的信息。
package com.example.ObjectOriented.KeyWord; public class anli2 { public static void main(String[] args) { Student student = new Student("张三",18,"男",89,45,36); student.show(); } } class Student{ private String name; private int age; private String gender; private double english; private double math; private double chinese; /** * 打印信息 */ public void show(){ System.out.println("name="+"\t"+this.name+"\t age="+this.age+"\t gender="+this.gender +"\t english="+this.english+"\t math="+this.math+"\t chinese="+this.chinese); } /** * 总分 */ public double getSum(){ return this.english+this.math+this.chinese; } /** * 平均分 */ public double avg(){ return this.getSum()/3; } public Student() { } public Student(String name, int age, String gender, double english, double math, double chinese) { this.name = name; this.age = age; this.gender = gender; this.english = english; this.math = math; this.chinese = chinese; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public double getEnglish() { return english; } public void setEnglish(double english) { this.english = english; } public double getMath() { return math; } public void setMath(double math) { this.math = math; } public double getChinese() { return chinese; } public void setChinese(double chinese) { this.chinese = chinese; } }
public static void main(String[] args) {
Student student = new Student("张三",18,"男",89,45,36);
student.show();
System.out.println(student.getSum());
System.out.println(student.getAge());
}
运行结果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix