0

I was following a tutorial and got incredibly confused when this technique was used, can anyone tell me what this is called and why this would be implemented? The following is an example:

Class Main:

package test;

public class Main {

//happens right here
    public Test testMethod() {
        Test test = new Test();
        test.setSomeVariable(2);
        return null;
    }
    
}

Class Test:

package test;

public class Test {
    private int someVariable = 2;
    
    public int getSomeVariable() {
        return someVariable;
    }
    
    public void setSomeVariable(int amount) {
        someVariable = amount;
    }
}

Essentially there is a call to the class in the same manner a method is used. It's not a constructor, as there is a method declaration following it.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Sokmixtp
  • 57
  • 5
  • 4
    I think you are just confused about return types. `testMethod` is a method of the `Main` class which returns an instance of the class `Test`. (well, in practice, always returns null) – Michael Jul 20 '21 at 14:29
  • There is no void, or type. The type is 'Test', this is where I am confused as test is not a type. – Sokmixtp Jul 20 '21 at 14:31
  • 5
    @Sokmixtp Test is a type. All classes are types. – Michael Jul 20 '21 at 14:31
  • Ahah thank you, I'm not sure how I've never encountered this. I'll have to experiment with it, thanks for your help – Sokmixtp Jul 20 '21 at 14:32
  • 2
    @Sokmixtp as a counterexample without a user-defined class: what if you need to return a string? `String` itself is a class. If classes weren't types you wouldn't be able to write a method that returns a string. – Federico klez Culloca Jul 20 '21 at 14:32
  • Relevant: [Difference between class and type](https://stackoverflow.com/questions/16600750/difference-between-class-and-type) – Michael Jul 20 '21 at 14:33
  • "There is a call to the class in the same manner a method is used. It's not a constructor, ..." - if you refer to `new Test()` then this _is_ a call to a constructor that is added implicitly by because `Test` doesn't have any explicit constructor. It creates an instance of `Test` which then assigned to the variable `test` and which you then can call the instance method `setSomeVariable(...)` on. – Thomas Jul 20 '21 at 14:41

1 Answers1

0

A method can return any type of data, including objects.

For example, when we write "int" in place of the method return type, it indicates the method will return an integer value.

If we write a class name in place of the method return type, it indicates the method will return an object of that class.

In your example, "Test" is the type. According to the return type of "testMethod()", this will return an object of type "Test".

To learn more about returning a class object from a method, please check the following tutorial

Java - Returning Objects from methods

Md. Faisal Habib
  • 1,014
  • 1
  • 6
  • 14