Let's say I have an abstract class A
exposing a method called getE()
which returns an object of type E
which is an enum
. The value returned by getE()
will be defined per subclass. Put differently, every object of a certain subclass of A
will always return the same value if getE()
is called.
This is how I have implemented that system right now:
public enum E {
VAL_1, VAL_2
}
public abstract class A {
private final E e;
protected A(E e) {
this.e = e;
}
public E getE() {
return e;
}
}
public class A1 extends A {
public A1() {
super(E.VAL_1);
}
}
public class A2 extends A {
public A2() {
super(E.VAL_2);
}
}
But this wastes memory, as every instance of A
has to keep a reference to E
, and also clutters A
's constructor.
Another solution I have thought of is this one:
public abstract class A {
public abstract E getE();
}
public class A1 extends A {
@Override
public E getE() {
return E.VAL_1;
}
}
public class A2 extends A {
@Override
public E getE() {
return E.VAL_2;
}
}
But adding new methods to a class probably is memory-intenisve as well and might cause confusion.
Which of these ways do you think is better or are there other alternatives?
I have already asked this question on Code Review and Stack Overflow and got redirected to here.