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.

arshajii
  • 127,459
  • 24
  • 238
  • 287
Kraishan
  • 443
  • 5
  • 14
  • 38
  • define the colors in C and make a getColor method in c which returns the colors – LoremIpsum Jun 19 '13 at 14:25
  • You can have a class `Z` that extends from `JPanel` and only adds a `C cHasTheColors` field, then classes `A` and `B` can extend from `Z` having all the power of `JPanel` and the `C` field in them (of course, if this is want you wanted to have). – Luiggi Mendoza Jun 19 '13 at 14:35
  • What if you make the classes A and B generic? At runtime, you pass them the color you want to. – Dimitri Jun 19 '13 at 14:40

2 Answers2

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.

Community
  • 1
  • 1
Dan O
  • 6,022
  • 2
  • 32
  • 50
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.

JavaNewbie_M107
  • 2,007
  • 3
  • 21
  • 36