定义一个学生类(Student),属性包括:学号,姓名,性别,年龄;方法包括:获得学号,获得姓名,获得性别,获得年龄,修改学号,修改姓名,修改性别,修改年龄。定义并创建一个学生数组对象,长度可自定,最后在控制台输出学生信息。
package project04;class Student{private String name;private String xh;private String xb;private int age;//类的封装public String getname() { //姓名return this.name;}public void setname(String name) {this.name=name;}//学号:public String getxh() { return this.xh;}public void setxh(String xh) {this.xh=xh;}//性别:public String getxb() { return this.xb;}public void setxb(String xb) {this.xb=xb;}//年龄public int getage() {return this.age;}public void setage(int age) {this.age=age;}//信息获取public Student(String xh,String name,String xb,int age) {setxh(xh); //获取学号setname(name); //获取姓名setxb(xb); //获取性别setage(age); //获取年龄}}public class Student1 {public static void main(String[] args) {Student p[]=new Student[4]; //创建数组,并确定数组长度p[0]=new Student("202112","小明","男",18); //创建对象p[0],并赋值。p[1]=new Student("202113","小红","女",18); //创建对象p[1],并赋值。p[2]=new Student("202114","小丽","女",16); //创建对象p[2],并赋值。p[3]=new Student("202115","小高","男",19); //创建对象p[3],并赋值。for(int i=0;i<4;i++) {System.out.println("学号:"+p[i].getxh()+" 姓名:"+p[i].getname()+" 性别:"+p[i].getxb()+" 年龄:"+p[i].getage());}}}
结果:
来源地址:https://blog.csdn.net/m0_73886399/article/details/129970394