0

I’m trying to figure out the below code. ImageIcone called “non-static method” getImage() according to Java API without any instance variable:

public void paintComponent(Graphics g) {
    Image img = new ImageIcon("imgtest.jpg", "description...").getImage();
    g.drawImage(img,3,4,this);
} 
2
  • 2
    What? What non static method? What is it invoked on? Commented Jun 9, 2014 at 2:33
  • getImage() in ImageIcon class Commented Jun 9, 2014 at 2:36

3 Answers 3

3

This

new ImageIcon("imgtest.jpg", "description...")

creates an instance. The getImage() method is invoked on that instance and then all references to that instance are lost. The object can then be garbage collected if it is unreachable.

Remember, all you need to invoke an instance method is an expression that resolves to an object reference. A variable of a reference type is one such expression. A constructor invocation is another such expression. An invocation of a method with a return type of some reference type is also such an expression.

Sign up to request clarification or add additional context in comments.

3 Comments

@ElliottFrisch The Image has a reference to the ImageIcon it came from? I don't know this API at all.
Because Image is abstract. See also ImageIcon.getImage()
thanks guys. also I hadn't noticed that it is an abstract class
3

You don't need an 'instance variable.' You only need an instance, and new ImageIcon("imgtest.jpg", "description...") is the instance.

Comments

0

In your code,you are creating an anonymous object of ImageIcon class by using the code new ImageIcon("imgtest.jpg", "description..."). Since you are not going to use that object in future,that's why you are opting to create an anonymous object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.