J
J
Jake Taylor2020-06-18 21:08:45
Java
Jake Taylor, 2020-06-18 21:08:45

How to access ENUM which is inside a class?

How to access ENUM which is inside a class?

There is a class Student , which has a ChildrenElements enum inside :

public class Student extends GeneralElement {
    private String name;
    private String surname;
    private String age;
    private String course;
    private String faculty;

    Student(){
        super.nameMainElement = "STUDENT";
    }

    protected void setCourse(String value) {
        this.course = value;
    }

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

    protected void setSurname(String value) {
        this.surname = value;
    }

    protected void setAge(String value) {
        this.age = value;
    }

    protected void setFaculty(String value) {
        this.faculty = value;
    }

    @Override
    public String toString(){
        return "\nName: " + name +
                "\nSurname: " + surname +
                "\nAge: " + age +
                "\nCourse: " + course +
                "\nFaculty: " + faculty;
    }

    public enum ChildrenElements {
        NAME,
        SURNAME,
        AGE,
        COURSE,
        FACULTY;
    }
}


How can I access the ChildrenElements enum in another class (like Main ) ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Orkhan, 2020-06-18
Hasanly @azerphoenix

Well, I see 2 options here:
1)

Student student = new Student();

// Student.ChildrenElements.COURSE;
// Например
String enumStr = Student.ChildrenElements.COURSE.toString();
int enumOrdinal = Student.ChildrenElements.COURSE.ordinal();

2) Either reflection

J
Jake Taylor, 2020-06-20
@n199a

Why doesn't it work?
There is a generic interface GeneralElement :

public interface GeneralElement {
   String getMainElement();
}

There are 2 classes that implement this interface. Student
class :
public class Student implements GeneralElement {
// тут переменные

public enum ChildrenElements {
        NAME,
        SURNAME,
        AGE,
        COURSE,
        FACULTY;
    }
}

User class :
public class Student implements GeneralElement {
// тут переменные

public enum ChildrenElements {
        LOGIN,
        PASSWORD;
    }
}

Why can't it be used like this?
public void create(GeneralElement general) {
for (general.ChildrenElements enumVar : general.ChildrenElements.values()) {
          System.out.println(enumVar); 
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question