Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Ok so why do coders do these differently? public class EXAMPLE extends JFrame{ J

ID: 3689217 • Letter: O

Question

Ok so why do coders do these differently?

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:

If you delare the variables/objects out side of methods/constructors, these variables/objects scope will be available throught out the program/class.

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);

In the above program, button1, button2, button 3 we declared as global variables instead of location variables. So we can use them anywhere we need them in program.

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);

If you consider the above the scope of these buttons variables/objects only available in Contructor method only. That is why we mentioned these objects at the begining og the program.

A local variable is defined within the scope of a block. It cannot be used outside of that block.

Global variables once declared they can be used any where in the program i.e. even in many functions. If possible u can use the global variables in the different user defined header files as like in packages in java.
On the other hand global variables values can be changed programmatically

local variables are local to a functional and cant be used beyond that function.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote