【JAVA】42、实例讲解——类设计分析

来源:互联网 发布:c语言常用命令 编辑:程序博客网 时间:2024/06/04 19:30

本篇博文最后修改时间:2016年3月23日,23:58。


一、简介

本篇介绍实例讲解——类设计分析。


二、实验平台
系统版本:Windows7 家庭普通版 32位操作系统。

三、版权声明
博主:思跡
声明:喝水不忘挖井人,转载请注明出处。
原文地址:http://blog.csdn.net/omoiato

联系方式:315878825@qq.com

Java零基础入门交流群:541462902


四、实例讲解——类设计分析

1、分析思路

①根据要求写出类所包含的属性

②所有的属性都必须进行封装(private)

③封装之后的属性通过setter和getter设置和取得

④如果需要可以加入若干构造方法

⑤再根据其他要求添加相应的方法

⑥类中的所有方法都不要直接输出,而是交给被调用出输出。


2、题目:

定义并测试一个名为Strudent的类,包括的属性有“学号”、“姓名“以及3门课程”数学“、”英语“和”计算机的成绩,包括的方法有计算3门课程的”总分“、”平均分“、”最高分“及”最低分“。

①本类中的属性及类型


②定义出需要的方法(普通方法、构造方法)

在本例中设计2个构造方法,一个是无参的构造方法,另外一个构造方法可以为5个属性进行赋值


按照以上类图,编写具体的代码如下:

范例:实现代码

class Student//定义学生类{private String stuno;//学生编号private String name;//学生姓名 private float math;//数学成绩private float english;//英语成绩private float computer;//计算机成绩public Student (){}//定义有5个参数的构造方法,为类中的属性初始化public Student(String stuno, String name, float math, float english, float computer){this.setStuno(stuno);//设置编号this.setName(name);//设置姓名this.setMath(math);//设置数学成绩this.setEnglish(english);//设置英语成绩this.setComputer(computer);//设置计算机成绩}public void setStuno(String s)//设置编号{stuno = s;}public void setName(String n)//设置姓名{name = n;}public void setMath(float m)//设置数学成绩{math = m;}public void setEnglish(float e)//设置英语成绩{english = e;}public void setComputer(float c) //设置计算机成绩{computer = c;}public String getStuno()//取得编号{return stuno;}public String getName()//取得姓名{return name;}public float getMath()//取得数学成绩{return math;}public float getEnglish()//取得英语成绩{return english;}public float getComputer()//取得计算机成绩{return computer;}public float sum()//计算机总分{return math + english + computer;}public float avg()//计算平均分{return this.sum() / 3;}public float max()//最高成绩{float max = math;max = max > computer? max : computer;//使用三目运算符max = max > english? max : english;//使用三目运算符return max;}public float min()//最低成绩{float min = math;min = min < computer? min : computer;//使用三目运算符min = min < english? min : english;//使用三目运算符return min;}}public class ExampleDemo01{public static void main(String args[]){Student stu = null;//声明对象//实例化Student对象,并通过构造方法赋值stu = new Student("MLDN - 33", "李兴华", 95.0f, 89.0f, 96.0f);System.out.println("学生编号:" + stu.getStuno());System.out.println("学生姓名:" + stu.getName());System.out.println("数学成绩:" + stu.getMath());System.out.println("英语成绩:" + stu.getEnglish());System.out.println("计算机成绩:" + stu.getComputer());System.out.println("最高分:" + stu.max());System.out.println("最低分:" + stu.min());}}
程序运行结果:


以上程序只是为大家简单地介绍了类的基本分析思路,实际问题肯定会复杂得多。

此时,就需要大家耐心分析,只有掌握好面相对象中的各个概念,才可以对程序代码进行更加合理的分析与设计。

0 0