免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2716 | 回复: 0
打印 上一主题 下一主题

Java中类设计 步骤 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-01-01 11:31 |只看该作者 |倒序浏览

程序的开发步骤:
   1.根据需求定义所要的类
   2.根据题目中的要求规划出类的属性
   3.所有的属性必须封装:private
   4.所有的属性必须通过getter和setter访问
   5.如果需要增加构造方法,为属性赋值
   6.所有的信息不要在类中直接输出,而是交给调用处输出
       |-在类中不能出现System.out.println()语句。
范例:
要求设计一个学生的类,里面有学生的三项成绩:计算机成绩、数学成绩、英语成绩
要求可以求总分、平均分、最高分、最低分,并且可以输出一个学生的完整信息。

类Student代码如下:
public class Student {
   
    private String name;
    private int age;
    private float computer;
    private float math;
    private float english;
   
    public Student(String n,int a,float c,float m,float e){
       this.setAge(a);
       this.setName(n);
       this.setComputer(c);
       this.setEnglish(e);
       this.setMath(m);
    }
    public float sum(){             //求总分
       return getComputer()+getEnglish()+getMath();   
   }
    public float avg(){           //求平均分
       return this.sum()/3;
    }
    public float max(){          //求最高分
       float max=computer>math?computer:math;
       max=max>english?max:english;
       return max;
    }
    public float min(){            //求最低分
       float min=computerenglish?computer:english;
       min=minmath?min:math;
       return min;
    }
    public String print(){
       return "学生信息:\n"+getName()+"、"+getAge()
                     +"\n"+getComputer()+"、"+getEnglish()+"、"+getMath();
    }
   
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public float getComputer() {
      return computer;
   }
   public void setComputer(float computer) {
      this.computer = computer;
   }
   public float getEnglish() {
      return english;
   }
   public void setEnglish(float english) {
      this.english = english;
   }
   public float getMath() {
      return math;
   }
   public void setMath(float math) {
      this.math = math;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
类ExecDemo代码如下:
public class ExecDemo {
   public static void main(String[] args) {
      
       Student stu =new Student("张三",21,90.4f,99f,67f);
       System.out.println(stu.print());
       System.out.println("最高分:"+stu.max());
       System.out.println("最低分:"+stu.min());
       System.out.println("平均分:"+stu.avg());
   }

}


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/106716/showart_2137182.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP