练习:44

练习对自定义类,私有属性,类的多参方法的使用

  • 需要注意形参和实参的顺序,类型,个数一致,就掌握了带参方法的使用。
  • 初学时,用很少的几个参数即可,熟练了,可适度增加。不建议一开始就定义十个形参,那样可能会不知方向。
  • 示例代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    /*
     * 包含自定义类+私有属性+类的多参方法
     */
    public class NewTest{
        private int num ;//定义数字编号,并私有化属性
        private String name ;//定义名字
        private String sex ;//定义性别
        public NewTest (int num,String name,String sex){ //多参方法,!()内为形参_即形象参数!
            this.num = num ; //this用于指定将参数里面的num赋给变量里面的num.
            this.name=name;//同上
            this.sex=sex;//同上
        }
       
        public void show (){ //无参方法用于输出
            System.out.println("数字编号:"+num);
            System.out.println("名字:"+name);
            System.out.println("性别:"+sex);
        }
       
        public static void main (String[]args){
            NewTest center = new NewTest (100,"sam","男");//创建对象,!定义实参_即实际参数!
            center.show();//调用方法输出
        }
    }