简体   繁体   中英

Solution to extend multiple classes

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.

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 Color s would have to be static and final .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM