Java - Extend class with enum

I have a class BaseNumber with a protected static enum Base, and another class ArithmeticBaseNumber extends BaseNumber.
I can access the Base enum from BaseNumber, however not from ArithmeticBaseNumber.
Is there a way to access the enum?
Thank you!

Edit - The code:

public class BaseNumber {
    protected static enum Base {
        X, Y, Z
    }
}
public class ArithmeticBaseNumber extends BaseNumber {}

The problem is that BaseNumbe.Base.X works fine, however ArithmeticBaseNumber.Base.X gives "The type ArithmeticBaseNumber.Base is not visible" error.

Upvotes: 0

Views: 74

Answers (3)

Ralf Kleberhoff
Ralf Kleberhoff

Reputation: 7290

The one enum type you're defining is BaseNumber.Base and not ArithmeticBaseNumber.Base nor simply Base.

So just reference it by its proper name BaseNumber.Base, and everything is fine.

You can (but probably shouldn't) make the simple name Base work by importing:

    import mypackage.BaseNumber.Base;

Caveat: if you want to use the short name, I'd typically recommend moving the Base enum out into its own file - to me, the dotted syntax is an important reminder that we're talking about some internal element of BaseNumber.

As a similar case, for readability reasons, I always stay with Map.Entry instead of Entry (unclear that it's related to Maps) or HashMap.Entry (plain wrong, Entry isn't part of HashMap).

Upvotes: 0

prem30488
prem30488

Reputation: 2856

It can be accessed. Try below example.

package com.example.demo.enumexample;

public class BaseNumber {
protected static enum Base{
FIRST("first"),
SECOND("second"),
THIRD("third");
String httpMethodType;
Base(String s) {
    httpMethodType = s;
}
public String getHTTPMethodType() {
    return httpMethodType;
}
}

public static void main(String[] args) {
    Base baseNum = Base.FIRST;
    System.out.println(baseNum);
}
}

And in ArithmeticBaseNumber.java

package com.example.demo.enumexample;

import com.example.demo.enumexample.BaseNumber.Base;

public class ArithmeticBaseNumber extends BaseNumber{
public static void main(String[] args) {
    Base baseNum = Base.FIRST;
    System.out.println(baseNum);
}
}

Output will be :

FIRST

In your example code,

package com.example.demo.enumexample;

public class BaseNumber {
protected static enum Base{
    X, Y, Z;

}

public static void main(String[] args) {
    Base baseNum = Base.X;
    System.out.println(baseNum);
}
}

And

package com.example.demo.enumexample;


public class ArithmeticBaseNumber extends BaseNumber{
public static void main(String[] args) {
    Base baseNum = Base.X;
    System.out.println(baseNum);
}
}

Output will be :

X

Upvotes: 0

Lev
Lev

Reputation: 86

Java doesn't support the inheritance of static members, a static member is callable on a class in which it has been created.

Upvotes: 1

Related Questions