首页 > 代码库 > Java- 基本封装

Java- 基本封装

package test.studet_manager;

public class Student {
    static int num = 100;
    // 编号-->唯一的
    private  int number = -1;
    //姓名
    private String name = "";
    //性别
    private String sex = "";
    //年龄
    private int age = -1;
    //班级
    private String grade = "";
    //成绩
    private int score = -1;

    /*
     *  set和 get的方法
     */
    public void setSex(String sex) {
        this.sex = sex;
    }
    
    public String getSex() {
        return sex;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
    
    public void setAge(int age) {
        // 年龄必须大于零
        if (age>=0) {
            this.age = age;
        }
        
    }
    
    public int getAge() {
        return age;
    }
    
    public void setGrade(String grade) {
        
        this.grade = grade;
    }
    
    public String getGrade() {
        return grade;
    }
    
    public void setScore(int score) {
        if (score >= 0) {
            this.score = score;
        }
        
    }
    
    public int getScore() {
        return score;
    }
    
    public void setNumber(int number) {
        this.number =this.number+0;
    }
    public int getNumber(){
        return number;
    }
    
    public Student() {
        // TODO Auto-generated constructor stub
        ++num;
        this.number = num;
    }
    public  Student(int number,String name,String sex,int age,String grade,int score) {
        getNumber();
        getName();
        getSex();
        getAge();
        getGrade();
        getScore();
    } 
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return ""+this.number+"  "+this.name+"  "+this.sex+"  "+this.age+"  "+this.grade+"  "+this.score+"\n";
    }
    
    @Override
    public boolean equals(Object obj) {
        // TODO Auto-generated method stub
        // 判断要比较的对象是不是null
        if (obj == null) {
            return false;
        }
        //判断要比较的对象是不是自己本身
        if (obj == this) {
            return true;
        }
        // 判断要比较的对象是不是同一类型
        if (obj instanceof Student) {
            Student student = (Student)obj;
            return student.number==this.number&&student.name==this.name&&student.sex==this.sex&&student.age==this.age&&student.grade==this.grade&&student.score==this.score;
        }
        return false;
    }
    @Override
    // 注意:hashCode方法与equals方法中的属性必须一致
    public int hashCode() {
        // TODO Auto-generated method stub
        return this.number-this.name.hashCode()-this.sex.hashCode()-this.age-this.grade.hashCode();
    }
    // 写一些自身的方法
    public void learn() {
        System.out.println(this.name+"在学习计算机语言");
    }
}

 

Java- 基本封装