S
S
STVDI2020-07-16 16:31:18
Java
STVDI, 2020-07-16 16:31:18

Why does one class not see the variables of another?

I am learning on the well-known JAVA site and I don’t understand why MainActivity doesn’t see the variables from Question.java
I know that the question is stupid, but I don’t understand myself (
W6g4MC0.png
v0lzia7.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Vodakov, 2020-07-16
@STVDI

Because:
1. A class is not just a file in which the code is written. Until you have created an object (an instance of a class), it does not exist, as well as its variables (with the exception of static variables).
2. To access variables of another class, you must access them through this class, for example:

Question question = new Question();
....
public boolean isCorrect(Question quest) {
    return quest.correctAnswer == quest.playerAnswer;
}

3. Thirdly, in your case, you should not write at all as you wrote, or as I showed in paragraph 2, the isCorrect method should be a method of the Question class and be called as: quest.isCorrect ()
And if it seemed to you that I answered better than Sergey Gornostaev , then you are mistaken. He is completely right, read the tutorials, and on that site you can consolidate your knowledge, although even for this your own pet project is better.

S
Sergey Gornostaev, 2020-07-16
@sergey-gornostaev

Because you teach Java on a well-known site, and not from a textbook.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question