Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access enum inside an interface

I am completely new to Java. I have an interface that has a few methods that I need to implement. Inside the interface, there is a class that has enums that I need to access.

It looks like this:

public interface Operations{
    //some function names that I have to implement
    public static enum ErrorCodes{
        BADFD;
        NOFILE;
        ISDIR;
        private ErrorCode{
        }
    }
}

In my implementation, when I try to access ErrorCodes.BADFD it gives me error. I do not know the right way to access it. Also, what is the empty private ErrorCode{} called. Is it the constructor? What does it do?

EDIT : added uppercase 'o' to enum name

like image 211
Neo Avatar asked Sep 02 '26 09:09

Neo


2 Answers

First, let's correct your malformed code:

// lowercase "interface"
// Usually interfaces and classes are capitalized
public interface Operations{
    // Singular to match the rest of the code and question.
    public static enum ErrorCode{
        // commas to separate instances
        BADFD,
        NOFILE,
        ISDIR;
        // Parameterless constructor needs ()
        private ErrorCode() {
        }
    }
}

To reference ErrorCode outside of the interface, you must qualify it with ErrorCode's enclosing interface, Operations.

Operations.ErrorCode code = Operations.ErrorCode.BADFD;
like image 99
rgettman Avatar answered Sep 05 '26 00:09

rgettman


Here is the corrected one

public interface Operations{
//some function names that I have to implement
public static enum ErrorCodes{
    BADFD,
    NOFILE,
    ISDIR;
    private ErrorCodes(){}
}
like image 32
Raghu K Nair Avatar answered Sep 04 '26 23:09

Raghu K Nair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!