A program needs an object with both static and non-static data. All data-classes should implement/extend the same class/interface so to be able to do:
Color color1 = new Navy();
To simplify it, lets take color storing classes an a Example. These color classes store a color and can calculate a custom mixture from their own and a passed color.
interface Color {
public static final int hex;
public int mix;
}
class Navy implements Color {
public static final int hex = 0x000080;
public int mix;
public Navy(int otherColor) {
mix = otherColor -128 +hex;
}
}
class Maroon implements Color {
public static final int hex = 0x800000;
public int mix;
public Maroon(int otherColor) {
mix = otherColor -56 +hex;
}
}
class DarkMagenta implements Color {
public static final int hex = 0x8B008B;
public int mix;
public DarkMagenta(int otherColor) {
mix = otherColor +180 +hex;
}
}
I know that all variables in an interface are static final and when using abstract classes, it is possible to declare an abstract method that has to be implemented but not an abstract variable.
What is a commonly good solution that doesn't require getters for everything and saves writing code?
EDIT:
Both the interface way:
interface Color {
public static final int hex=0;
public int mix=0;
}
class Navy implements Color {
public static final int hex = 0x000080;
public int mix;
public Navy(int otherColor) {
mix = otherColor -128 +hex;
}
}
class Maroon implements Color {
public static final int hex = 0x800000;
public int mix;
public Maroon(int otherColor) {
mix = otherColor -56 +hex;
}
}
class DarkMagenta implements Color {
public static final int hex = 0x8B008B;
public int mix;
public DarkMagenta(int otherColor) {
mix = otherColor +180 +hex;
}
}
and the abstact class way:
abstract class Color {
public static final int hex=0;
public int mix;
}
class Navy extends Color {
public static final int hex = 0x000080;
public int mix;
public Navy(int otherColor) {
mix = otherColor -128 +hex;
}
}
class Maroon extends Color {
public static final int hex = 0x800000;
public int mix;
public Maroon(int otherColor) {
mix = otherColor -56 +hex;
}
}
class DarkMagenta extends Color {
public static final int hex = 0x8B008B;
public int mix;
public DarkMagenta(int otherColor) {
mix = otherColor +180 +hex;
}
}
do not do what i want:
//this works but
Navy color1 = new Navy(9);
System.out.println(color1.hex);// 128
// not this
Color color2 = new Navy(9);
System.out.println(color2.hex);// 0
All colors should be a child member of Color.