J. Doe
J. Doe

Reputation: 19

How to create a correct instance in Java?

I am learning Java and found this article on stackoverflow.

So there are two classes:

public class Image {

...

    public Image clone() {
        Image clone = new Image(getMagicNumber(), getHeight(), getWidth(), getMax());
        for (int i = 0; i < getHeight(); i++){

            for (int j = 0; j < getWidth(); j++){
                clone.setPixel(getPixel(i, j), i, j);
             }
        }
        return clone;
    }
}

And than there is this class:

public class Filter {

    public Filter() {

    }

    public Image linearFilter(Image image, float[][] kernel) {
        Image filtered = image.clone();

        ...

         return filtered;
    }
}

I am used to do X instancename = new X(); for creating an instance, where X is the name of the class. Are there different ways for creating an instance? For example in the Filter class: How is Image filtered = image.clone(); creating an instance? In order to create an instance I thought on both sides of the "equation" X has to be equal. What I mean by this: Image filtered = new Image();. I don't understand how Image filtered = image.clone(); is creating a new instance. Can someone explain?

Upvotes: 1

Views: 194

Answers (2)

Dheeraj Joshi
Dheeraj Joshi

Reputation: 1582

class: How is Image filtered = image.clone(); creating an instance?

It is creating an instance as you can see that the method clone() is returning the type Image, the first line of the method is showing this :

Image clone = new Image(getMagicNumber(), getHeight(), getWidth(), getMax());

and at last of this method clone is returned,this was the logic

I hope it helps

Upvotes: 1

meditat
meditat

Reputation: 1165

Image filtered = image.clone();

Is same as

Image filtered = new Image();

you can see thet clone() is a method of your class which return the instance of the class Image

But making instance using methods like clone() are supportive when you want to create only one instance of your class, you can make the instance of your class public and final, and return it using a public method.

Upvotes: 1

Related Questions