OK so now I understand GLOBAL variables and Local Variables. Now what would happ
ID: 3689478 • Letter: O
Question
OK so now I understand GLOBAL variables and Local Variables. Now what would happen is I declare my gloabal variables as private?
public class EXAMPLE extends JFrame{
JButton button1;
JButton button2;
JTextField xfield;
public EXAMPLE(){
super("The title");
setLayout(new FlowLayout());
button1 = new JButton("num1");
add(button1);
button2 = new JButton("num2");
add(button2);
xfield = new JTextField(15);
add(xfield);
AND
public class EXAMPLE extends JFrame{
public EXAMPLE(){
super("The title");
setLayout(new FlowLayout());
JButton button1 = new JButton("num1");
add(button1);
JButton button2 = new JButton("num2");
add(button2);
JTextField xfield = new JTextField(15);
add(xfield);
Explanation / Answer
Answer:
You can declare private access specifier on global variables. But the scope of that variable only to the class to which they belong. you can not access these variables from other classes. If you want to use these variable which you mentioned as private then you have to create setter and getter methds for the same class and through that class object you can access them.
Example:
private Access Modifier:
Here is an example of assigning the private access modifier to a field:
Accessing private Fields via Accessor Methods
Fields are often declared private to control the access to them from the outside world. In some cases the fields are truly private, meaning they are only used internally in the class. In other cases the fields can be accessed via accessor methods (e.g. getters and setters). Here is an accessor method example:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.