1

Let's say I have Class A and B that differ except on using color variables. Both classes already extend the JPanel Class so I cannot extend a new class with the color variables in it. I then thought I could make class C (with the colors in it) an interface. But it's not allowed to have attributes in an interface.

Any idea how I can still use the colors in an external class for both Class A + B?

The thought:

Class A - Uses the colors
Class B - Uses the colors
Class C - Has the colors.

4

2 回答 2

0
public interface C {
  public static final Color c1 = Color.RED;
  public static final Color c2 = Color.GREEN;
  public static final Color c3 = Color.BLUE;
}

public class A extends JPanel implements C {
    /* ... */
}

public class B extends JPanel implements C {
    /* ... */
}

EDIT: As noted in Luiggi Mendoza's comment, your Colors would have to be static and final.

于 2013-06-19T14:23:25.200 回答
0

You can always use an interface for storing constants.

public interface C{
    Color a;
    Color b; 
    //And so on
}

Now have A and B implement this class, and that should do it.

于 2013-06-19T14:23:49.733 回答