7
Icon bug = new ImageIcon( getClass().getResource( "bug1.png" ) );
ImageIcon bug = new ImageIcon( getClass().getResource( "bug1.png" ) );

What's the difference between these two? My book always uses the way in the first line to declare an ImageIcon but wouldn't it be better to declare it the second way because more specifically it is an ImageIcon?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
stumped
  • 3,235
  • 7
  • 43
  • 76
  • 1
    The first way tells anybody looking at your code that you'll only be using methods from the `Icon` class - that is, the fact that this `Icon` happens to be an `ImageIcon` is irrelevant to the code. This is a maintainability boon. It also means you can do refactorings into methods that are more widely useful - ones where you pass in an `Icon` instead of an `ImageIcon`. – Dawood ibn Kareem Dec 30 '13 at 01:05
  • 2
    `Icon` is an interface; `ImageIcon` is a class that implements that interface. Here's another SO question that tackles the issue of why you'd declare a variable to have the interface type instead of the concrete type: http://stackoverflow.com/questions/3768869/use-interface-or-type-for-variable-definition-in-java – ajb Dec 30 '13 at 01:06

5 Answers5

6

Icon is an Interface, whereas ImageIcon is an implementation of that interface.

The first is better because it means you can change your ImageIcon for another implementation of Icon later without needing to change the rest of your application.

sasankad
  • 3,543
  • 3
  • 24
  • 31
1
Their nature and application is different. Image is an abstract superclass of all classes that represent graphical images. ImageIcon is an implementation of Icon interface that uses Image as its source.
Think of an Image as something that could be rendered and an ImageIcon as something that will be rendered as an Icon when its paintIcon() method is called.

Quoted from here
Hope this is what you're looking for ;)

Community
  • 1
  • 1
Levi
  • 1,921
  • 1
  • 14
  • 18
1

You should start by taking a read through JavaDocs for ImageIcon.

You will notice that ImageIcon implements Icon, meaning that it can be used where ever an Icon is expected (such as JButton and JLabel for example) but it also provides the means by which you can obtain an instance of Image which allows you to paint it using Graphics without the need for a Component reference, which Icon needs

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

see java-imageicon-vs-image-difference

It is a thread about the difference between image and imageicon, but in the comments they also talk about Icon and such. Maybe this helps.

Community
  • 1
  • 1
Chris M
  • 52
  • 6
0

both are similar but the first one is the best because ImageIcon is Icon but not the reverse.When i say ImageIcon is Icon ImageIcon implements Icon.

Yirga
  • 881
  • 1
  • 12
  • 31