-1

I have this class (call it child) that extends the JComboBox class from the Swing library in Java. Now when I create an object of child and try to call the method addItem(Object) on it by passing in a String, I get the following warning:

Type safety: The method addItem(Object) belongs to the raw type JComboBox. References to generic type JComboBox<E> should be parameterized.

What is the proper way of invoking this method? I can't instantiate child with the generic type of <String> because child is not generic; I don't see how else to do this. Any help would be appreciated.

PS. Changing contents of child is not an option.

Bazinga
  • 489
  • 1
  • 5
  • 16
  • 1
    `class MyClass extends JComboBox` – resueman Jun 14 '16 at 14:25
  • "Changing contents of `child` is not an option" – Bazinga Jun 14 '16 at 14:25
  • 2
    Then ignore the warning and move on. If you can't change `child`, and have to use instances of `child`, then there's nothing you can do. – Laf Jun 14 '16 at 14:30
  • 2
    You probably don't want to extend JComboBox at all but rather your class should "have-a" `JComboBox`, since it is *usually* preferred to favor composition over inheritance. Please see Wikipedia article: [Composition over Inheritance](https://en.wikipedia.org/wiki/Composition_over_inheritance), and two StackOverflow links: [Prefer composition over inheritance?](http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance) and [Favor composition over inheritance](http://stackoverflow.com/questions/11343840/favor-composition-over-inheritance). – Hovercraft Full Of Eels Jun 14 '16 at 14:36

1 Answers1

0

What you want is to make your child class a child of JComboBox<String>, not just JComboBox. This will stop the little warning for popping up.

Example:

public class Child extends JComboBox<String>{

}

When you do this, all the generic methods, fields and so on will now be a String and not an Object.

Edit:

I see you said that you cannot change the child class. This makes things rather difficult.

There isn't really a straightforward way of doing this, even workarounds will ultimately still display this warning. Your one option (that i can see) is use to use the @SuppressWarnings("unchecked") annotation above the code producing the warning. This will stop the warning from showing up.

Luke Melaia
  • 1,470
  • 14
  • 22