是否可以访问枚举的值?

时间:2019-12-28 02:24:19

标签: java oop enums

我有这个代码

    enum check
{
   STUDENT ("Sireee"), ID (12354), YEAR ("1st Year"), DEP("College of Computer Studies");
   private String year;
   private String student;
   private String dep;
   private int id;
 // some Constructor here 

我的问题是我不知道如何在主类中获取STUDENT,ID,YEAR和DEP的值。如何能够得到这个值? enter image description here

结果为enter image description here

我的**期望的输出**是

父亲

12345

第一年

计算机学院

2 个答案:

答案 0 :(得分:5)

您使用错误的方式使用enum。在您的情况下,最好使用class

Student.java

public class Student {

    private int id;
    private String name;
    private String year; // int is prefered. since you are using string I used it.
    private Department dep; // demonstrating use of enum

    // getters and setters
}

现在,让我们看看如何使用enum

Department.java

public enum Department {

    CSE("Computer Science Engineering"),
    MEC("Mechanical Engineering")

    private String name;

    Department(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

如果您希望现在显示值,让我们创建两个学生并显示值

public class Test {

    public static void main(String[] args) {
        Student s1 = new Student();
        s1.setName("John Wick");
        s1.setId(1);
        s1.setYear("1st Year");
        s1.setDepartment(Department.CSE);

        Student s2 = new Student();
        s2.setName("Will Smith");
        s2.setId(2);
        s2.setYear("2nd Year");
        s2.setDepartment(Department.MEC);

        System.out.println(s1.getName() + " department is " + s1.getDepartment().getName());
        System.out.println(s2.getName() + " department is " + s2.getDepartment().getName());
    }
}

Output

John Wick department is Computer Science Engineering
Will Smith department is Mechanical Engineering

答案 1 :(得分:0)

enter image description here

感谢您的所有回答,我得以解决此问题,并做了一些实验,令我惊讶的是它确实有效<3 enter image description here