I have a class that extends another one. It should have an enum that should have certain values for the extending class, so I have the following:
public class Shepherd extends Dog {
public enum Color {
BLACK,
GREEN,
INVISIBLE
}
// ...
}
This enum should be a part of the extending class, as another class that extends Dog
should have its own enum with its own values, that's why I can't make the Color
enum a part of the Dog
class. For example:
public class Corgi extends Dog {
public enum Color {
RED,
BLACK,
SABLE
}
// ...
}
Also, I have a constructor:
public class Shepherd extends Dog {
public enum Color {
// ...
}
public Shepherd(Color color) {
super(color);
}
// ...
}
I need the base class (Dog
) to have the color
field that would be accessible from other methods of the same base class (Dog
).
public class Dog {
public enum Color { } // not sure in that :-(
private Color color;
public Dog(Color color) {
this.color = color;
}
public Color getColor() {
return this.color;
}
// ...
}
Obviously, it won't work, as Dog.Color
is not the same type as Shepherd.Color
. OK, let's do it another way:
public class Shepherd extends Dog<Shepherd> {
// ...
public Shepherd(Color color) {
super(color);
}
// ...
}
public class Dog<T extends Dog> {
public enum Color { } // ???
private T.Color color;
public Dog(T.Color color) {
this.color = color;
}
public T.Color getColor() {
return this.color;
}
// ...
}
And I'm still getting incompatible types: Shepherd.Color cannot be converted to Dog.Color
. :-( Why doesn't Java accept it? The parameter has type T.Color
, which should mean Shepherd.Color
or Corgi.Color
dependent on the class we use, isn't it?
Would anyone be so kind as to show me the correct way with an example? Thanks in advance!