java编写一个学生类,包括学号姓名和班级

学生类的定义

Java中,可以通过编写一个学生类来实现对学生信息的管理和维护。学生类通常包含学号、姓名和班级三个属性,分别对应着每个学生的个人信息。在Java中,我们可以使用类的定义来实现这一目的,定义一个名为Student的类,并在其中声明这三个属性。

public class Student{
    private int id;     //学号
    private String name;    //姓名
    private String className;   //班级

    //构造方法
    public Student(int id, String name, String className){
        this.id = id;
        this.name = name;
        this.className = className;
    }

    //get方法
    public int getId(){
        return id;
    }

    public String getName(){
        return name;
    }

    public String getClassName(){
        return className;
    }

    //set方法
    public void setId(int id){
        this.id = id;
    }

    public void setName(String name){
        this.name = name;
    }

    public void setClassName(String className){
        this.className = className;
    }
}

学生类的使用

一旦定义了学生类,就可以在程序中创建学生对象,并对其属性进行赋值和访问。

java编写一个学生类,包括学号姓名和班级

public class Main{
    public static void main(String[] args){
        //创建学生对象
        Student stu = new Student(20190101, "张三", "软工1901班");

        //读取学生信息
        System.out.println("学生信息:");
        System.out.println("学号:" + stu.getId());
        System.out.println("姓名:" + stu.getName());
        System.out.println("班级:" + stu.getClassName());

        //修改学生信息
        stu.setName("李四");
        stu.setClassName("软工1902班");

        //再次读取学生信息
        System.out.println("学生信息:");
        System.out.println("学号:" + stu.getId());
        System.out.println("姓名:" + stu.getName());
        System.out.println("班级:" + stu.getClassName());
    }
}

学生类的拓展

在实际应用中,学生类可以根据需要进行拓展,例如添加其他属性,比如性别、生日、联系电话等,或者添加方法,比如获取年龄、计算平均分等。另外,还可以通过使用集合或者数组来实现对多个学生信息的管理,比如构建一个学生数组或者学生集合,对其中的学生进行增删改查、排序等操作。

public class Student{
    private int id;     //学号
    private String name;    //姓名
    private String className;   //班级
    private String sex;     //性别
    private String birthday;    //生日
    private String phone;   //联系电话
    private float mathScore;   //数学成绩
    private float englishScore;    //英语成绩
    private float computerScore;   //计算机成绩

    //构造方法
    public Student(int id, String name, String className, String sex, String birthday, String phone){
        this.id = id;
        this.name = name;
        this.className = className;
        this.sex = sex;
        this.birthday = birthday;
        this.phone = phone;
    }

    //get方法和set方法
    //......

    //获取年龄
    public int getAge(){
        //计算年龄
        //..
        return age;
    }

    //计算平均分
    public float getAverageScore(){
        float avg = (mathScore + englishScore + computerScore) / 3;
        return avg;
    }
}

本文来自投稿,不代表亲测学习网立场,如若转载,请注明出处:https://www.qince.net/javaw2ljjava.html

郑重声明:

本站所有内容均由互联网收集整理、网友上传,并且以计算机技术研究交流为目的,仅供大家参考、学习,不存在任何商业目的与商业用途。 若您需要商业运营或用于其他商业活动,请您购买正版授权并合法使用。

我们不承担任何技术及版权问题,且不对任何资源负法律责任。

如遇到资源无法下载,请点击这里失效报错。失效报错提交后记得查看你的留言信息,24小时之内反馈信息。

如有侵犯您的版权,请给我们私信,我们会尽快处理,并诚恳的向你道歉!

(0)
上一篇 2023年4月24日 下午11:34
下一篇 2023年4月24日 下午11:34

猜你喜欢