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?
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?
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.