Search code examples
javaobjectinstantiation

Is it acceptable to instantiate an object by copying from the return value from a method?


I'm new at Java and I recently learnt about constructors in my uni class. I tried write a code to instantiate an object with arguments. The script get the inputs as arguments with Scanner instance.

The problem is, if I create a method to instantiate an object inside of it, the object would be treated as a local variable of the method. If I create a method to get arguments only and instantiate the object in the main method with them, it becomes somewhat messy. My solution is to create a method which is 1. getting inputs, 2. instantiating an object with constructor, and 3. returning the object just created. I could got a result what I've wanted but I am not sure this is acceptable or not.

Here is my code:

public class Game {
    private int gameID;
    private String gameTitle;
    private String genre;

    // constructor
    public Game(int ID, String title, String genre) {
        gameID = ID;
        gameTitle = title;
        this.genre = genre;
    }
}
import java.util.Scanner;

public class GameTest {

    static Scanner kb = new Scanner(System.in);

    public static void main(String[] args) {
        Game myGame = constructGame();
    }


    static Game constructGame() {

        int ID = kb.nextInt();
        kb.nextLine();
        String title = kb.nextLine();
        String genre = kb.nextLine();

        Game newGame = new Game(ID, title, genre);

        return newGame;
    }
}

Can this solution be a problem? Honestly, I'm bit worried about memory references things here.


Solution

  • This is completely acceptable. It would perhaps be cleaner if constructEmployee took the Scanner it uses as a parameter, and then the main method would pass the scanner to it, but there's nothing wrong per-se with your current code.