Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - class name in method declaration where the return type should be

I am working on some code where there is a method that looks like this:

    public static ProcessorClass getProcessor(String x, int y) {
     return(var);
    }

From what I remember the way this is written the "ProcessorClass" is a return type but what does that mean. The "ProcessorClass" is the class that the method is currently in. I am confused in what this means.

like image 643
Angela Avatar asked Oct 12 '25 08:10

Angela


1 Answers

Check this example, which is an implementation of the Singleton pattern:

public class Ploop
{
    private final int x;
    private static Ploop instance = null;

    public int getX()
    {
        return x;
    }

    public static Ploop getInstance()
    {
        if(instance == null) instance = new Ploop();
        return instance;
    }

    private Ploop()
    {
        x = 0;
    }
}

In this case, the getInstance() function is the only way to get a new Ploop object. If the constructor were public, then there would be two ways, new Ploop() and Ploop.getInstance().

Because the getInstance() only instantiates Ploop once, there can only ever be one instance of Ploop. (Barring unusual ways of instantiating an object, like through reflection...)

Another way to make use of this pattern is to allow a class to use the Builder pattern to instantiate itself in phases.

Does this make anything clearer?

like image 95
Tripp Kinetics Avatar answered Oct 15 '25 01:10

Tripp Kinetics