Skip to main content
gamedev.net
🔒 Locked

Java Class Constructor Question

Started by Matthew Melendez Feb 2, 2012 at 8:36 PM 3 replies 1.3k views
Original Post
Matthew Melendez
Matthew Melendez
Can anyone find any problems that make arise with this code?
Will there be a problem with an empty constructor like this?

package foo;


import java.awt.Image.*;
import java.awt.image.BufferedImage;
public class foo
{
BufferedImage image = new BufferedImage(64,32,BufferedImage.TYPE_INT_ARGB);


public foo()
{
//no code here
}
public void setRgb(int x, int y, int rgb)
{
image.setRGB(x,y,rgb);
}
}


I want to be able to create a new foo object like so:

foo object = new foo();


and be able to do this:

object.setRgb(5,5,0x00000000)
Florian22222
Florian22222
There won´t be an error. Although it´s not a good programming style.
The better way is to call the constructor of the image in your own constructor like this:

package foo;

import java.awt.Image.*;
import java.awt.image.BufferedImage;
public class foo
{
BufferedImage image;

public foo()
{
image = new BufferedImage(64,32,BufferedImage.TYPE_INT_ARGB)
}
public void setRgb(int x, int y, int rgb)
{
image.setRGB(x,y,rgb);
}
}


Hope I could help you!
Matthew Melendez
Matthew Melendez

There won´t be an error. Although it´s not a good programming style.
The better way is to call the constructor of the image in your own constructor like this:

package foo;

import java.awt.Image.*;
import java.awt.image.BufferedImage;
public class foo
{
BufferedImage image;

public foo()
{
image = new BufferedImage(64,32,BufferedImage.TYPE_INT_ARGB)
}
public void setRgb(int x, int y, int rgb)
{
image.setRGB(x,y,rgb);
}
}


Hope I could help you!


I tired that and the setRgb() method can't find the image object. I think it might be out of scope of the setRgb() method.
WavyVirus
WavyVirus
I haven't used the AWT classes, but in general the setRgb method should be able to use the image object. Can you post any error message which is generated?
rip-off
rip-off

The better way is to call the constructor of the image in your own constructor like this:
[/quote]
It is about the same. This is stylistic really.


I tired that and the setRgb() method can't find the image object. I think it might be out of scope of the setRgb() method.
[/quote]
Did you leave "image" as a field or did you accidentally make it local to the constructor?

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.