zoukankan      html  css  js  c++  java
  • 深入理解带参方法-----对象作为参数的方法

    在了解过普通的带参方法后,我们再次将视角拉到深入带参方法中。

     在数组作为参数的方法里面我们知道了可以将多个学生的成绩添加到数组中并打印出来,

    那么如果现在不仅要添加学生的成绩,还要添加学生的年龄和成绩,如何实现呢?

    面对这样的问题我们就可以使用面向对象的思想,把所有要添加的学生信息封装到学生类中,只需要在方法中传递一个学生对象就可以包含所有的信息。

    接下来就来看看到底应该怎样实现吧。

     1 public class Student {
     2     //学生类
     3     public int id;
     4     public String name;
     5     public int age;
     6     public int score;
     7     public void showinfo(){
     8         System.out.println(id+"	"+name+"	"+age+"	"+score);
     9     }
    10 
    11 
    12 public class StudentsBiz {
    13     /**
    14      * 学生管理类
    15      */
    16     Student[] students = new Student[30];
    17     
    18     //增加学生
    19     public void addstudent(Student stu){
    20         for (int i = 0; i < students.length; i++) {
    21             if (students[i]==null) {
    22                 students[i]=stu;
    23                 break;
    24             }
    25         }
    26     }
    27     
    28     //显示本班的学生信息
    29     public void showStudents(){
    30         System.out.println("本班的学生列表");
    31         for (int i = 0; i < students.length; i++) {
    32             if (students[i]!=null) {
    33                 students[i].showinfo();
    34             }
    35         }
    36         System.out.println();
    37     }
    38 
    39 
    40 
    41 public static void main(String[] args) {
    42         /**
    43          * 对象作为参数的方法
    44          * 示例5.
    45          * 实例化学生对象并初始化
    46          */
    47           Student student1 = new Student();
    48           student1.id=10;
    49           student1.name="王二";
    50           student1.age=18;
    51           student1.score=99;
    52           
    53           Student student2 = new Student();
    54           student2.id=11;
    55           student2.name="张三";
    56           student2.age=18;
    57           student2.score=100;
    58           
    59           //新增学生对象
    60           StudentsBiz biz = new StudentsBiz();
    61           biz.addstudent(student1);
    62           biz.addstudent(student2);
    63           biz.showStudents();
    64     }

    面向对象的思想要提升绝非一时之功,得需勤加练习!

  • 相关阅读:
    倒计时发送短信案例
    倒计时效果
    setInterval 定时器
    setTimeout定时器
    调整窗口大小事件
    window常见事件onload
    模拟京东快递单号查询
    模拟京东按键输入内容
    跟随鼠标的天使案例
    Vue 事件监听实现导航栏吸顶效果(页面滚动后定位)
  • 原文地址:https://www.cnblogs.com/john69-/p/5177248.html
Copyright © 2011-2022 走看看