Android Build a Simple Android App with Java Basic Android Programming Making a Button Do Something

sebbe12
sebbe12
4,015 Points

Why do he declear TexView before using it instead of declearing it at the time when used. Less code feels better

So instead or writting

private TextView factTextView; private Button showAnotherFactButton; // and then

factTextView = findViewById(R.id.factTextView); showAnotherFactButton = findViewById(R.id.btn_fact);

Why not do this

TextView factTextView = findViewById(R.id.factTextView); Button showAnotherFactButton = findViewById(R.id.btn_fact);

Is it because we can't use private this way. Don't see a point in using private tho. Is it simply just easier to understand for beginners?

2 Answers

Hi sebbe12 . The reason has to do with the scope of the variable. It all depends on where this variable is going to be used in the class.

  • Declaring it at a class level (above onCreate()), making it a member variable, means it will be accessible anywhere in the class.
  • Declaring it inside a method (or any block of code defined by curly brackets {}), making it a local variable, means its scope (or accessibility/visibility) is limited to that block of code, so it will cease to exist outside of it.

If you want to access a variable in other parts of your class (outside onCreate()), you must declare it at a class level. For instance, if you want to declare a method in your class to modify the text in that factTextView or define another method for what to do when you click that showAnotherFactButton, you'll need to declare these 2 variables as member variables, at the top of the class. Have a look at this short video to understand it better.

As for the access modifier, it defines the scope of the variable within the application this time (not just the class):

  • public = it is accessible from all classes in the app
  • private= it is only accessible in its own class (common practice, for encapsulation. As bot .net said, making the variables (and methods) private allows us to hide those from other users, making sure they won't break that part they do not need to worry or know about)
  • protected = it is accessible within this package

Hope that helps :)

bot .net
bot .net
12,822 Points

Hi, Im by no mean an expert but i can answer some of ur points:

U use the keyword private as a default accessor, u want to make all ur fields private in default because 2 things: u can change it later to public or other accessors without break the code u protect the variable from being changed and accessed from other parts in ur code.

I think he used it in that way to make it organized and i agree about this decision. first he declare the variable then assigned the action.

hope this helps