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.
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!