static来实现学号累加,班级一样等功能

定义学生类。输入该班级学生基本信息,其中学号累加,班号一样

首先定义学生类。包含基本信息姓名,年龄

要使得班号一样,那么应该在学生类中加上静态static关键字。可以定义成static String room;

要使得学号累加。则可以定义一个累加计数器。首先呢还是得先定义私有变量学号id:private int id;多个累加计数器,可以先赋值为0,然后在构造函数实现累加:private static int idCount = 0;

如何在构造函数实现累加:
这里我定义了一个无参构造函数和一个全参构造函数(当然不包括学号和班级,他们俩比较特殊)

public Demo02Student(String name, int age) {
    this.name = name;
    this.age = age;
    this.id = ++idCounter;
}

public Demo02Student(){
this.id = ++idCounter;
}

定义学生类的全代码:

package cn.itcast.day0607.demo04;

public class Demo02Student {
    private String name;
    private int age;
    static String room;
    private int id;
    private static int idCounter = 0;
    public Demo02Student(){
        this.id = ++idCounter;
    }

    public Demo02Student(String name, int age) {
        this.name = name;
        this.age = age;
        this.id = ++idCounter;
    }

    public static String getRoom() {
        return room;
    }

    public static void setRoom(String room) {
        Demo02Student.room = room;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

在调用的时候记得,因为room是静态static修饰的,因此是属于类的,那只要在一个赋值,其他的都一样改变了。但是要注意,需要在调用类的第一个实例对象就赋值,否则会出现空指针异常的情况。

调用Demo02Student类的全代码:

package cn.itcast.day0607.demo04;

public class Demo02StaicUse {
    public static void main(String[] args) {
        Demo02Student stu1 = new Demo02Student("张三",18);
        Demo02Student stu2 = new Demo02Student("李四",19);
        stu1.room = "102教室";
        System.out.println("姓名为:"+stu1.getName()+",年龄为:"+stu1.getAge()
        +",教室为:"+stu1.getRoom()+",学号为:"+stu1.getId());
        System.out.println("姓名为:"+stu2.getName()+",年龄为:"+stu2.getAge()
        +",教室为:"+stu2.getRoom()+",学号为:"+stu2.getId());

    }
}

运行结果如图:
在这里插入图片描述

谢谢你们的检阅~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值