-3

I am new in java, and please ask me what this code is mean?

Image img = new ImageIcon("2.png")

how can image class type link create another object?

Til
  • 5,150
  • 13
  • 26
  • 34

1 Answers1

1

A variable of type Image can refer to an instance of ImageIcon if ImageIcon either extends or implements Image (directly or indirectly). (I should note that the only ImageIcon class I know, javax.swing.ImageIcon does not and so that code wouldn't compile. Presumably you're using something else.)

In general, a superclass-typed variable can refer to a subclass object, and an interface-typed variable can refer to any object whose class implements that interface. This is vital for polymorphism in Java.

I suggest going through the Java Inheritance Tutorial for more. You may also find my answer to this other question useful.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • but what is different if i will write like this - ImageIcon img = new ImageIcon("2.png") – Sasun Hakobyan Feb 03 '19 at 16:13
  • @SasunHakobyan - I suspected that might be what the rest of that comment was going to be. :-) See [this question's answers](https://stackoverflow.com/questions/1348199/what-is-the-difference-between-the-hashmap-and-map-objects-in-java), in particular [mine](https://stackoverflow.com/questions/1348199/what-is-the-difference-between-the-hashmap-and-map-objects-in-java/1348228#1348228). – T.J. Crowder Feb 03 '19 at 16:15