Non-static methods, (seemingly) not called on an object

Greetings!

I am working on “Cumulative Project 4” of “Build Android Apps with Java” and looking at steps 10 and 11 (out of 21).

Access this exercise below.

https://www.codecademy.com/paths/introduction-to-android-with-java/tracks/java-arrays-and-loops/modules/cumulative-project-4/projects/unquote-game-logic-pt-ii

In the code below, from this exercise (steps 10 and 11), it seems like a non-static method (generateRandomNumber()) is being called in a static way in that it is being called, but not on an object instance (int n = generateRandomNumber(questions.size() - 1).

How does this work? I feel like the answer is obvious and has been explained in coursework, but something just isn’t connecting for me here.

Thank you in advance for any assistance!
Mike

Hello @mschaef8, welcome to the forums! Could you post your full code, please? To format code in the forums correctly, see this thread.

Thank you @codeneutrino. My apologies…

public Question chooseNewQuestion(){
    int n = generateRandomNumber(questions.size() - 1);
    currentQuestionIndex = n;
  return questions.get(n);
  }

Where do you call chooseNewQuestion()? Is it within the main() method, or another method within the class?

1 Like

chooseNewQuestion() is defined and called in MainActivity.java. It is called w/in the startNewGame() w/in the same file, MainActivity.java. See below:

public void startNewGame(){
    Question question1 = new question(921238, "How tall is the Eiffel tower?", "10ft", "1063ft", "30ft", "333ft", 1);
    Question question2 = new question(107343, "Who invented the computer algorithm?", "Joe", "Sam", "Alan Turing", "Ada Lovelace", "King Henry", 3);
    Question question3 = new question(748294, "What is the name for the patch of skin found on your elbow?", "elbow skin", "wenis", "todd", "none of the above", 1);
    ArrayList<Questions> startNewGameQuestions = new ArrayList<Questions>();
    questions = startNewGameQuestions;
    startNewGameQuestions.add(question1);
    startNewGameQuestions.add(question2);
    startNewGameQuestions.add(question3);
    totalCorrect = 0;
    totalQuestions = 0;
    Question firstQuestion = chooseNewQuestion();

If you’re calling a non-static method in another non-static method of the same class, you don’t need a instance. Take this trivial example:

public class Main {
    public String x(){
        return "he";
    }
    public void xy(){
        System.out.println( x() + "he");
    }
    public static void main(String[] args) {
        Main z = new Main();
        z.xy();//this prints "hehe"
    }
}

See how, although x() is not static, the only place we call it is in the non-static xy() method, which is still a method of the Main class.
I hope this helps!